//
//  DataManager.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/10/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "DataManager.h"
#import <AdSupport/AdSupport.h>

#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseQueue.h"

#import "AppManager.h"
#import "KeyObject.h"
#import "ProductObject.h"
#import "SizeObject.h"
#import "WebServiceManager.h"
#import "UserObject.h"
#import "ShopObject.h"
#import "TipView.h"
#import "WaitTooles.h"
#import "PMGlobal.h"

#import "SuitObject.h"
#import "config.h"
#import "JSONKit.h"

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

static DataManager *_sharedManager = nil;

@interface DataManager(){
    FMDatabase *db_;
    
    NSArray *datas_;
    
    NSMutableArray *orders_;
    NSMutableArray *favorites_;
    
    UserObject *userObject_;
    
    NSArray *shops_;
    
    NSArray *productUpdates_;
    NSArray *productColorids_;
    NSArray *productPictures_;
    NSArray *spdmstatustimeUpdates_;
    NSArray *suitUpdates_;
    NSArray *orderUpdates_;
    NSArray *TipUpdates_;
    NSArray *spdmorderUpdates_;
    NSArray *g_sizeUpdates_;
    
    ShopObject * currentshop_;
    NSString *address;
}

@end

@implementation DataManager

+ (DataManager *)sharedManager {
    @synchronized( [DataManager class] ){
        if(!_sharedManager)
            _sharedManager = [[self alloc] init];
        return _sharedManager;
    }
    return nil;
}

+ (id)alloc {
    @synchronized ([DataManager class]){
        NSAssert(_sharedManager == nil,
                 @"Attempted to allocated a second instance");
        _sharedManager = [super alloc];
        return _sharedManager;
    }
    return nil;
}

- (id)init {
    self = [super init];
    if (self) {
        NSString *bundlePath = [[AppManager sharedManager] getBundleDatabasePath];
        NSString *localPath = [[AppManager sharedManager] getDatabasePath];
        if (![[NSFileManager defaultManager]fileExistsAtPath:localPath]) {
            NSError *err = nil;
            [[NSFileManager defaultManager] copyItemAtPath:bundlePath toPath:localPath error:&err];
        }
        
        db_ = [FMDatabase databaseWithPath:localPath];
        if (![db_ open]) {
            db_ = nil;
        }
        
        datas_ = nil;
        
        
#ifdef DEBUG
//        [self refreshSizeTable:^(id res){
//            NSLog(@"更新r_size表");
//        }];

//更新组合搭配档案
//        [self refreshSuitTable:^(id res){
//            NSLog(@"更新配装档案");
//        }];

//更新过滤条件档案
//        [self refreshReferenceTable:^(id res){
//            
//        }];

//更新商品基础档案
//        [self refreshProductTable:^(id res){
//            NSLog(@"更新商品基础档案");
//        }];
        
//更新商品颜色基础档案
//        [self refreshProductColoridTable:^(id res){
//            NSLog(@"更新商品颜色基础档案");
//        }];
        
//更新商品图片基础档案
//        [self refreshProductPictureTable:^(id res){
//            NSLog(@"更新商品图片基础档案");
//        }];
        
//更新商品颜色表
//        [self refreshColortblTable:^(id res){
//            NSLog(@"更新商品颜色表");
//        }];

//更新商品系类表
//        [self refreshXilieTable:^(id res){
//            NSLog(@"更新商品系类表");
//        }];
        
//更新商品款式表
//        [self refreshKuansTable:^(id res){
//            NSLog(@"更新商品款式表");
//        }];
        
//更新商品款型表
//        [self refreshKuanxTable:^(id res){
//            NSLog(@"更新商品款型表");
//        }];
        
//更新商品小系列表
//        [self refreshXiaoxlTable:^(id res){
//            NSLog(@"更新商品小系列表");
//        }];
        
//更新商品年份表
//        [self refreshNianfTable:^(id res){
//            NSLog(@"更新商品年份表");
//        }];
        
//更新商品季节表
//        [self refreshJijieTable:^(id res){
//            NSLog(@"更新商品季节表");
//        }];
        
//更新商品品牌表
//        [self refreshPingpTable:^(id res){
//            NSLog(@"更新商品品牌表");
//        }];
        
//更新商品投产状态
//        [self refreshSpdmStatusTimeTable:^(id res){
//            
//        }];

//更新商品尺码表
//        [self refreshSpdmSizeTable:^(id res){
//            NSLog(@"更新商品尺码表成功");
//        }];
        
//        [self refreshSpdmOrderTable];
        
//         [self refreshTipsTable];
        
//        [self forceUpdate:^(id res){
//            NSLog(@"");
//        }];
        
#endif

    }
    return self;
}

- (KeyObject *)createKeyObject:(FMResultSet *)rs{
    KeyObject *obj = [[KeyObject alloc] init];
    obj.keyID = [rs intForColumn:@"ID"];
    obj.keyName = [rs stringForColumn:@"Name"];
    obj.keyIndex = [rs intForColumn:@"Seq"];
    obj.categoryCode = [rs intForColumn:@"Category"];
    obj.parentCode = [rs intForColumn:@"FatherID"];
    obj.columnname = [rs stringForColumn:@"ColumnName"];
    return obj;
}


- (ProductObject *)createProductObjectByDic:(NSDictionary *)dic{
    ProductObject *obj = [[ProductObject alloc] init];
    obj.keyObject = dic;
    obj.pNote = [dic objectForKey:@"note"];
    obj.pName = [dic objectForKey:@"codename"];
    NSNumber *n = [dic objectForKey:@"code"];
    obj.pCode = [dic objectForKey:@"code"];
    obj.pSale = [[dic objectForKey:@"sale"] floatValue];
    obj.pColor = [dic objectForKey:@"colorname"];
    if (obj.pColor==nil) {
        obj.pColor = @"";
    }
    n = [dic objectForKey:@"colorid"];
    NSLog(@"%@",[n class]);
    obj.pColorCode = [NSString stringWithFormat:@"%lld", [n longLongValue]];
    obj.pSerial = [dic objectForKey:@"c_xilmc"];
    obj.pType = [dic objectForKey:@"c_kuansmc"];
    obj.pSeason = [dic objectForKey:@"c_jijmc"];
    obj.pIntroDate = [dic objectForKey:@"c_nianfmc"];
    obj.pSizeGroupID = [[dic objectForKey:@"groupno"] intValue];
    obj.pRecommend = [dic objectForKey:@"c_pingpmc"];
//    if ([dic objectForKey:@"c_pingpbh"]) {
//        obj.pRecommendCode = [[dic objectForKey:@"c_pingpbh"] intValue];
//    }
    
    obj.simCode = [dic objectForKey:@"jm"];
    obj.mianliao = [dic objectForKey:@"c_mianlmc"];
//    obj.pRatio = [[dic objectForKey:@"ratio"] floatValue];
    obj.pURL = [dic objectForKey:@"c_url"];
    obj.pZhanting = [dic objectForKey:@"c_zhanting"];
    obj.pFengge = [dic objectForKey:@"c_fenggmc"];
    obj.pBanxing = [dic objectForKey:@"c_banxmc"];
    obj.pxilie = [dic objectForKey:@"c_pingpmc"];
    obj.n_status = [dic objectForKey:@"n_status"];
    obj.n_jiny = [dic objectForKey:@"n_jiny"];
    obj.n_beis = [dic objectForKey:@"n_beis"];
    if ([obj.n_beis intValue]== 0) {
        obj.n_beis = @"1";
    }
    obj.item5 = [dic objectForKey:@"item5"];
    return obj;
}

- (ProductObject *)createProductObject:(FMResultSet *)rs{
    return [self createProductObjectByDic:[NSDictionary dictionaryWithDictionary:[rs resultDictionary]]];
}

- (SizeObject *)createSizeObject:(FMResultSet *)rs{
    SizeObject *obj = [[SizeObject alloc] init];
    
    obj.sSizeNo = [rs stringForColumn:@"sizeno"];
    obj.sSizeName = [rs stringForColumn:@"sizetext"];
    obj.sGroupName = [rs stringForColumn:@"groupname"];
    return obj;
}

-(NSString *)createSetObject:(FMResultSet *)rs{
    NSString *str=[NSString stringWithFormat:@"%@",[rs stringForColumn:@"num"]];
    return str;
}
-(NSString *)createSizeGroupObject:(FMResultSet *)rs{
    NSString *str=[NSString stringWithFormat:@"%@",[rs stringForColumn:@"sizelist"]];
    return str;
}
//获取产品类型和款式信息
- (NSArray *)getKeyInfo{
    
    if (datas_) {
        return datas_;
    }
    
    if (db_==nil) {
        return nil;
    }
    
    NSMutableArray *array = [NSMutableArray array];
    
    FMResultSet *rs = [db_ executeQuery:@"select * from ReferencePara"];
    while ([rs next]) {
        KeyObject *obj = [self createKeyObject:rs];
        [array addObject:obj];
    }
    
    datas_ = [NSArray arrayWithArray:array];
    
    return datas_;
}

- (NSArray *)getKeyCategories{
    
    NSMutableArray *array = [NSMutableArray array];
    
    FMResultSet *rs = [db_ executeQuery:@"select DISTINCT Category from ReferencePara ORDER BY Category"];
    while ([rs next]) {
        NSString *s = [rs stringForColumnIndex:0];
        [array addObject:s];
    }
    return array;
}

- (NSMutableArray *)getKeyObjects:(int)categoryCode{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from ReferencePara WHERE Category = %d ORDER BY Seq",
                     categoryCode];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        KeyObject *obj = [self createKeyObject:rs];
        [array addObject:obj];
    }
    return array;
}

- (KeyObject *)getKeyObject:(int)keyID{
    NSString *sql = [NSString stringWithFormat:@"select * from ReferencePara WHERE ID = %d ORDER BY seq",
                     keyID];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        KeyObject *obj = [self createKeyObject:rs];
        return obj;
    }
    
    return nil;
}

- (NSMutableArray *)getChildrenKeyObjects:(int)keyID{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString
                     stringWithFormat:@"select * from ReferencePara WHERE FatherID = %d ORDER BY seq",
                     keyID];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        KeyObject *obj = [self createKeyObject:rs];
        [array addObject:obj];
    }
    return array;
}

- (int)getParentCategoryCode:(int)categoryCode{
    NSArray *arr = [self getKeyObjects:categoryCode];
    for (KeyObject *obj in arr) {
        if (obj.parentCode>0) {
            KeyObject *res = [self getKeyObject:obj.parentCode];
            if (res!=NULL) {
                return res.categoryCode;
            }
        }
    }
    
    return -1;
}

- (NSArray *)getProduct:(NSArray *)filters page:(int)page pageSize:(int)pageSize{
    NSMutableArray *array = [NSMutableArray array];

    NSString *sql = @"select distinct * from v_g_spdm where n_status<>2 and upper(code) not like '%%K'";
    
    NSString* condition = @" ";
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and %@ = '%@'",key.columnname,key.keyName ];
        }
        
    }
    
    sql = [sql stringByAppendingFormat:@"%@ group by code order by %@ LIMIT %d,%d ",condition,PRODUCT_SORT,page*pageSize,pageSize];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}
- (NSArray *)getProduct:(NSArray *)filters type:(NSString *)type page:(int)page pageSize:(int)pageSize{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select distinct * from v_g_spdm where c_xilmc = '%@' and upper(code) not like '%%K' order by %@ LIMIT %d,%d",type,PRODUCT_SORT,page*pageSize,pageSize];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

- (NSArray *)getProduct:(NSArray *)filters type:(NSString *)type style:(NSString *)style page:(int)page pageSize:(int)pageSize{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm where n_status<>2 and c_xilmc = '%@' and c_kuansmc = '%@' and upper(code) not like '%%K' order by  c_xilbh,code,colorid LIMIT %d,%d",type,style,page*pageSize,pageSize];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}


- (NSMutableArray *)getAllProduct:(ProductObject *)product{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and code = '%@'  order by %@",product.pCode,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

- (NSMutableArray *)getSimiliarProduct:(ProductObject *)product{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and code = '%@' AND trim(colorid) <> '%@'  order by %@",product.pCode,product.pColorCode,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

- (NSArray *)getSizeListBySizeGroup:(int)sizeGroupID SizeType:(NSString*)sizeType{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql;
    if (sizeType||[sizeType isEqualToString:@""]) {
        sql = [NSString stringWithFormat:@"select * from r_size WHERE groupno = %d  and groupname = '%@' order by cast(sizeno as int)",sizeGroupID,sizeType];
    }
    else
    {
        sql = [NSString stringWithFormat:@"select * from r_size WHERE groupno = %d  order by cast(sizeno as int)",sizeGroupID];
    }
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SizeObject *obj = [self createSizeObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

- (NSArray *)getSizeGroup{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = @"select distinct groupno from r_size";
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        [array addObject:[rs resultDictionary]];
    }
    
    return array;
}

- (NSArray *)getSizeTypeBySizeGroup:(int)sizeGroupID{
    NSMutableArray *array = [NSMutableArray array];    
    NSString *sql = [NSString stringWithFormat:@"select distinct trim(groupname) groupname from r_size WHERE groupno = %d  order by groupname",sizeGroupID];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *obj = [rs stringForColumn:@"groupname"];
        [array addObject:obj];
    }
    
    return array;
}

- (NSArray *)getSpdmOrder{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from spdmorder"];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        NSString *str = [rs stringForColumn:@"c_spdmmc"];
        [dic setObject:str forKey:@"c_spdmmc"];
        str = [rs stringForColumn:@"c_spdmzd"];
        [dic setObject:str forKey:@"c_spdmzd"];
        str = [rs stringForColumn:@"b_visible"];
        [dic setObject:str forKey:@"b_visible"];
        [array addObject:dic];
    }
    
    return array;
}

- (OrderObject *)createOrderByProduct:(ProductObject *)product ShopId:(NSString*)shopid{
    
    OrderObject* order = [self getOrderByProduct:product Shopid:shopid];
    
    return order;
}

- (void)placeOrder:(OrderObject *)order{

    for ( NSString *key in order.quantity.allKeys ) {
        NSArray *comps = [key componentsSeparatedByString:@"_"];
        NSString *sID = [comps objectAtIndex:1];
        NSString *sizeno = [comps objectAtIndex:0];
        
        int val = [[order.quantity objectForKey:key] intValue];
        
        [self addOrder:order withSizeNo:sizeno byAmout:val Shopid:sID];
    }

}

- (NSArray *)searchProductWithSimCode:(NSString *)key{

    NSMutableArray* arr = [[NSMutableArray alloc]init];
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and jm = UPPER('%@')  order by %@",key,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [arr addObject:obj];
    }
    
    return arr;
}

- (NSString *)searchProductCountWithSimCode:(NSString *)key{
    
    NSString *sql = [NSString stringWithFormat:@"select count(*) cnt from (select distinct code from v_g_spdm WHERE n_status<>2 and jm = UPPER('%@')) a group by code",key];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        
        return [rs stringForColumn:@"cnt"];
    }
    
    return nil;
}

- (NSArray *)searchProductWithCode:(NSString *)key{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and code LIKE '%%%@%%' and upper(code) not like '%%K' group by code  order by %@",key,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

- (ProductObject *)getProductObjectByName:(NSString *)pName andColor:(NSString*)color{
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and upper(code) = '%@' AND colorid = '%@'  order by %@",pName,color,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        return obj;
    }
    return nil;
}

- (void)setShopList:(NSArray *)shops{
    shops_ = shops;
}

- (NSArray *)getShopList{
    return shops_;
}

- (NSArray *)getWrittenShopList{
    NSMutableArray *array = [NSMutableArray array];
    for (ShopObject *obj in shops_) {
        if (!obj.bCheck&&[obj.bOrder intValue]==1) {
            [array addObject:obj];
        }
    }
    return array;
}

- (void)setCurrentShop:(ShopObject*)shop{
    currentshop_ = shop;
}

- (ShopObject *)getCurrentShop{
    return currentshop_;
}



-(NSArray *)GetSuitSimilarObject:(NSString *)scripno withType:(NSString *)type{
//    
//    "select b.code,b.colorid,g.c_url from g_billm_Assembling a left join g_billd_Assembling b on a.scripno=b.scripno left join v_g_spdm g on b.code=g.code and b.colorid=g.colorid";
//    
    NSString *sql = [NSString stringWithFormat:@"select a.scripno,a.type,a.code,a.colorid,g.c_url from g_billd_Assembling a left join v_g_spdm g on a.code=g.code and a.colorid=g.colorid where  a.scripno='%@' and g.n_status<>2 and a.type='%@'",scripno,type];
    FMResultSet *rs = [db_ executeQuery:sql];
    
    NSMutableArray *res = [NSMutableArray array];
    
    while ([rs next]) {
        SubSuitObject *obj = [[SubSuitObject alloc] init];
        
        obj.subSuitType = [rs stringForColumn:@"type"];
        obj.productCode = [rs stringForColumn:@"code"];
        obj.colorid = [rs stringForColumn:@"colorid"];

        obj.productImage = [rs stringForColumn:@"c_url"];
        obj.scriptNo = [rs stringForColumn:@"scripno"];
        
        [res addObject:obj];
    }
    
    return res;
}

- (NSArray *)getRecommendSuitArray{
    NSString *sql = [NSString stringWithFormat:@"select * from g_billm_Assembling where recommend = 1 order by rowid"];
    return [self getSuitArrayBase:sql];
}

- (NSArray *)getSuitArrayBase:(NSString *)sql{
    //    NSMutableArray *array = [NSMutableArray array];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SuitObject *suit = [[SuitObject alloc] init];
        
        suit.scriptNo = [rs stringForColumn:@"scripno"];
        //        suit.ioDate = [rs stringForColumn:@"iodate"];
        suit.n_id = [rs intForColumn:@"n_id"];
        suit.c_miaos = [rs stringForColumn:@"c_miaos"];
        suit.pic_path = [rs stringForColumn:@"pic_path"];
        suit.c_mingc = [rs stringForColumn:@"c_mingc"];
        suit.theme = [rs stringForColumn:@"theme"];
        suit.recommend = [rs stringForColumn:@"recommend"];
        
        //sql = [NSString stringWithFormat:@"select * from g_billd_Assembling where scripno = '%@' and flag = 1",suit.scriptNo];
        
        NSMutableArray *component = [[NSMutableArray alloc] init];
        suit.components = component;
        
        //        [array addObject:suit];
        [dic setObject:suit forKey:suit.scriptNo];
    }
    
    sql = [NSString stringWithFormat:@"select a.scripno,a.type,a.code,a.colorid,g.c_url from g_billd_Assembling a left join v_g_spdm g on a.code=g.code and a.colorid=g.colorid"];
    
    
    FMResultSet *subRes = [db_ executeQuery:sql];
    while ([subRes next]) {
        
        NSString *s = [subRes stringForColumn:@"scripno"];
        SuitObject * suitObj = [dic objectForKey:s];
        
        SubSuitObject *obj = [[SubSuitObject alloc] init];
        
        obj.subSuitType = [subRes stringForColumn:@"type"];
        obj.productCode = [subRes stringForColumn:@"code"];
        obj.colorid = [subRes stringForColumn:@"colorid"];
        obj.productImage = [subRes stringForColumn:@"c_url"];
        obj.scriptNo = [rs stringForColumn:@"scripno"];
        
        [suitObj.components addObject:obj];
    }

    
    NSComparator cmptr = ^NSComparisonResult(id o1, id o2){
        SuitObject *obj1 = (SuitObject *)o1;
        SuitObject *obj2 = (SuitObject *)o2;
        
        return obj1.n_id>obj2.n_id;
    };
    
    NSArray *res = [dic.allValues sortedArrayUsingComparator:cmptr];
    
    return res;
    
}

- (NSArray *)getSuitArray{
    NSString *sql = [NSString stringWithFormat:@"select * from g_billm_Assembling order by rowid"];
    return [self getSuitArrayBase:sql];
}


- (NSArray *)GetSuitArrayByCode:(NSString*)code ColorId:(NSString*)colorid{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select distinct a2.* from g_billd_Assembling a1 join g_billm_Assembling a2 on a1.scripno = a2.scripno where a1.code = '%@' and a1.colorid = '%@'",code,colorid];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SuitObject *suit = [[SuitObject alloc] init];
       
        
        suit.scriptNo = [rs stringForColumn:@"scripno"];
//        suit.ioDate = [rs stringForColumn:@"iodate"];
        suit.n_id = [rs intForColumn:@"n_id"];
        suit.c_miaos = [rs stringForColumn:@"c_miaos"];
        suit.pic_path = [rs stringForColumn:@"pic_path"];
        suit.c_mingc = [rs stringForColumn:@"c_mingc"];
        suit.theme = [rs stringForColumn:@"theme"];
        suit.recommend = [rs stringForColumn:@"recommend"];
        
        sql = [NSString stringWithFormat:@"select * from g_billd_Assembling where scripno = '%@' and flag = 1",suit.scriptNo];
        
        NSMutableArray *component = [[NSMutableArray alloc] init];
        FMResultSet *subRes = [db_ executeQuery:sql];
        while ([subRes next]) {
            SubSuitObject *obj = [[SubSuitObject alloc] init];
            
            obj.subSuitType = [subRes stringForColumn:@"type"];
            obj.productCode = [subRes stringForColumn:@"code"];
            obj.colorid = [subRes stringForColumn:@"colorid"];
            obj.productImage = [subRes stringForColumn:@"c_url"];
            obj.scriptNo = [rs stringForColumn:@"scripno"];
            
            [component addObject:obj];
        }
        
        suit.components = component;
        
        [array addObject:suit];
    }
    
    return array;
}

- (NSArray *)SearchSuitArrayByCode:(NSString*)code{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from g_billd_Assembling where code LIKE  '%%%@%%' and flag =1",code];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SuitObject *suit = [[SuitObject alloc] init];
        
        NSMutableArray *component = [[NSMutableArray alloc] init];
        SubSuitObject *obj = [[SubSuitObject alloc] init];
            
        obj.subSuitType = [rs stringForColumn:@"type"];
        obj.productCode = [rs stringForColumn:@"code"];
        obj.colorid = [rs stringForColumn:@"colorid"];
        obj.productImage = [rs stringForColumn:@"c_url"];
        obj.scriptNo = [rs stringForColumn:@"scripno"];
        
        [component addObject:obj];
        
        suit.components = component;
        
        [array addObject:suit];
    }
    
    return array;
}


- (NSArray *)getSuitArrayByFilter:(NSArray*)filters insuit:(BOOL)insuit{
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select distinct a2.* from g_billd_Assembling a1 join g_billm_Assembling a2 on a1.scripno = a2.scripno "];
    
    NSString* condition = @" ";
    
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            //第一个条件使用where
            if ([condition isEqualToString:@" "]) {
                
                condition = [condition stringByAppendingFormat:@" where a3.%@ = '%@'",key.columnname,key.keyName ];
            }
            else{
                condition = [condition stringByAppendingFormat:@" and a3.%@ = '%@'",key.columnname,key.keyName ];
            }
            
        }
    }
    
    //如果包含条件的话就关联商品档案表进行过滤
    if (![condition isEqualToString:@" "]) {
        if (insuit ==YES) {
            sql = [sql stringByAppendingFormat:@" join v_g_spdm a3 on a1.code = a3.code and a1.colorid = a3.colorid  %@ ",condition];
        }
        else
        {
            sql = [sql stringByAppendingFormat:@" join v_g_spdm a3,my_favorite a4 on a1.code = a3.code and a1.scripno = a4.code and a1.colorid = a3.colorid  %@ ",condition];
        }
    }
    else
    {
        if (insuit == NO) {
            sql = [sql stringByAppendingFormat:@" join my_favorite a4 on a1.scripno = a4.code"];
        }
    }
    
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SuitObject *suit = [[SuitObject alloc] init];
        
        suit.scriptNo = [rs stringForColumn:@"scripno"];
//        suit.ioDate = [rs stringForColumn:@"iodate"];
        suit.n_id = [rs intForColumn:@"n_id"];
        suit.c_miaos = [rs stringForColumn:@"c_miaos"];
        suit.pic_path = [rs stringForColumn:@"pic_path"];
        suit.c_mingc = [rs stringForColumn:@"c_mingc"];
        suit.theme = [rs stringForColumn:@"theme"];
        suit.recommend = [rs stringForColumn:@"recommend"];
        
        sql = [NSString stringWithFormat:@"select * from g_billd_Assembling where scripno = '%@' and flag = 1",suit.scriptNo];
        
        NSMutableArray *component = [[NSMutableArray alloc] init];
        FMResultSet *subRes = [db_ executeQuery:sql];
        while ([subRes next]) {
            SubSuitObject *obj = [[SubSuitObject alloc] init];
            
            obj.subSuitType = [subRes stringForColumn:@"type"];
            obj.productCode = [subRes stringForColumn:@"code"];
            obj.colorid = [subRes stringForColumn:@"colorid"];
            obj.productImage = [subRes stringForColumn:@"c_url"];
            obj.scriptNo = [rs stringForColumn:@"scripno"];
            
            [component addObject:obj];
        }
        
        suit.components = component;
        
        [array addObject:suit];
    }
    
    return array;
}



- (void)setUserObject:(NSString *)usercode name:(NSString *)username u_id:(NSString *)u_id shop:(NSArray *)shopid password:(NSString *)password{
    if (usercode==nil) {
        userObject_ = nil;
        return;
    }
    userObject_ = [[UserObject alloc] init];
    
    userObject_.userCode = usercode;
    userObject_.userName = username;
    userObject_.u_id = u_id;
    userObject_.shopID = shopid;
    userObject_.password = password;
    
    [self setShopList:shopid];
}

- (BOOL)login:(NSString *)userCode password:(NSString *)password u_id:(NSString *)u_id{
    NSString *sql = nil;
    if (password.length>0&&userCode) {
        sql = [NSString stringWithFormat:@"select * from s_user WHERE usercode = '%@' AND password = '%@'",userCode,password];
    }else if(userCode){
        sql = [NSString stringWithFormat:@"select * from s_user WHERE usercode = '%@' AND password is null",userCode];
    }
    else if(u_id)
    {
        sql = [NSString stringWithFormat:@"select * from s_user WHERE u_id = '%@'",u_id];
    }
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return YES;
    }
    
    return NO;
}

- (void)logout{
    userObject_ = nil;
}

- (UserObject *)getUserObject{
    return userObject_;
}


- (ProductObject *)getProductEx:(NSString *)pCode withColorID:(NSString*)colorid{
    NSString *sql = [NSString stringWithFormat:@"select g.code,g.sale,g1.colorid,r.colorname,i.c_url from g_spdm g left join g_spdmdetail g1 on g.code=g1.code left join r_colortbl r on g1.colorid=r.colorid  left join g_spdm_img i on g1.code=i.code and g1.colorid=i.colorid WHERE g.n_status<>2 and UPPER(g.code) = '%@' AND g1.colorid = '%@'",pCode,colorid];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        return obj;
    }
    
    return nil;
}

- (ProductObject *)getProduct:(NSString *)pCode withColorID:(NSString*)colorid{
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and UPPER(code) = '%@' AND colorid = '%@'  order by %@",pCode,colorid,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        return obj;
    }
    
    return nil;
}

- (int)isAddtionProduct:(NSString *)code{
    NSString *s = [code substringWithRange:NSMakeRange(1, 1)];

    return [s intValue];
}

- (NSString *)getNormalProductCode:(NSString *)pCode{
    NSMutableString *code = [NSMutableString string];
    for (int i = 0; i < pCode.length;i++) {
        NSString *s = [pCode substringWithRange:NSMakeRange(i, 1)];
        if (i==1) {
            s = @"0";
        }
        [code appendString:s];
    }
    return code;
}

- (NSDictionary *)getAdditionalProduct:(NSString *)pCode withColorID:(NSString *)colorid{
    
    NSMutableDictionary *res = [NSMutableDictionary dictionary];
    
    NSMutableString *code = [NSMutableString string];
    for (int i = 0; i < pCode.length;i++) {
        NSString *s = [pCode substringWithRange:NSMakeRange(i, 1)];
        if (i==1) {
            s = @"_";
        }
        [code appendString:s];
    }
    
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and code LIKE '%@' AND colorid = '%@'  order by %@",code,colorid,PRODUCT_SORT];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        
        NSString *code = [rs stringForColumn:@"code"];
        NSString *s = [code substringWithRange:NSMakeRange(1, 1)];
        
        if ([code isEqualToString:pCode]) {
            continue;
        }
        
        ProductObject *obj = [self createProductObject:rs];
        [res setObject:obj forKey:s];
    }
    
    return res;
}

- (ProductObject *)getProduct:(NSString *)pCode withColorID:(NSString*)colorid Filter:(NSArray*)filters{
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status<>2 and code = '%@' AND colorid = '%@'",pCode,colorid];
    
    NSString* condition = @" ";
    
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and %@ = '%@'",key.columnname,key.keyName ];
        }
        
    }
    
    condition = [condition stringByAppendingFormat:@"order by %@",PRODUCT_SORT];
    
    sql = [sql stringByAppendingString:condition];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        return obj;
    }
    
    return nil;
}

- (ProductObject *)getCanceledProduct:(NSString *)pCode withColorID:(NSString*)colorid Filter:(NSArray*)filters{
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm WHERE n_status=1 and code = '%@' AND colorid = '%@'",pCode,colorid];
    
    NSString* condition = @" ";
    
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and %@ = '%@'",key.columnname,key.keyName ];
        }
    }
    
    sql = [sql stringByAppendingString:condition];
    sql = [sql stringByAppendingString:[NSString stringWithFormat:@" order by %@",PRODUCT_SORT]];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        return obj;
    }
    
    return nil;
}



//- (NSArray *)getOrderedProducts:(NSString*)shopid Submit:(int)flag{
//    
//    NSMutableArray *array = [self getOrderedWithFilter:shopid Submit:flag filter:nil];
//    
//    for (NSDictionary *dic in array) {
//        ProductObject *p = [self getProduct:[dic objectForKey:@"code"] withColorID:[dic objectForKey:@"colorid"]];
//        [array addObject:p];
//    }
//    
//    return array;
//}

//- (NSArray *)getOrderedProducts:(NSString *)type style:(NSString *)style Shopid:(NSString*)shopid Submit:(int)flag{
//    NSMutableArray *array = [NSMutableArray array];
//    
//    NSMutableArray* arr = [self getOrdered:shopid Submit:flag];
//    
//    for (NSDictionary *dic in arr) {
//        
//        ProductObject *p = [self getProduct:[dic objectForKey:@"code"] withColorID:[dic objectForKey:@"colorid" ] type:type style:style];
//            if (p) {
//                [array addObject:p];
//            }
//    }
//    if (array.count == 0) {
//        return nil;
//    }
//    else
//    {
//    return array;
//    }
//}

- (int)getUnloadProduct:(NSString *)shopid{
    NSString *sql = [NSString stringWithFormat:@"select count(*) icount from g_meeting where shopid = '%@' and maxsynid = '' group by code",shopid];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    int count = 0;
    while ([rs next]) {
//        count = [rs intForColumn:@"icount"];
        count++;
    }
    return count;
}

- (NSArray *)getOrderedProducts:(NSArray*)Keys Shopid:(NSString*)shopid Submit:(int)flag{
    NSMutableArray *array = [NSMutableArray array];
    
    NSMutableArray* arr = [self getOrderedWithFilter:shopid Submit:flag filter:Keys];
    
    for (NSDictionary *dic in arr) {
        
        ProductObject *p = [self createProductObjectByDic:dic];
        [array addObject:p];
    }
    if (array.count == 0) {
        return nil;
    }
    else
    {
        return array;
    }
}

- (NSArray *)getCanceledOrderProducts:(NSArray*)Keys Shopid:(NSString*)shopid{
    NSMutableArray *array = [NSMutableArray array];
    
    NSMutableArray* arr = [self getOrderedWithFilter:shopid Submit:2 filter:Keys];
    
    for (NSDictionary *dic in arr) {
        
//        ProductObject *p = [self getCanceledProduct:[dic objectForKey:@"code"] withColorID:[dic objectForKey:@"colorid" ] Filter:Keys];
//        if (p) {
//            [array addObject:p];
//        }
        ProductObject *p = [self createProductObjectByDic:dic];
        [array addObject:p];
    }
    if (array.count == 0) {
        return nil;
    }
    else
    {
        return array;
    }
}



- (BOOL)excuteSQL:(NSString *)sql{
    BOOL res = [db_ executeUpdate:sql];
    return res;
}

-(NSString *)getUserNameByLocal:(NSString *)usercode{
    NSString *sql = [NSString stringWithFormat:@"select * from s_user where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        
        return [rs stringForColumn:@"username"];
    }
    return nil;
}

- (ShopObject *)getShopObjectByID:(NSString *)shopid{
    for (ShopObject *obj in shops_) {
        if ([obj.shopID isEqualToString:shopid]) {
            return obj;
        }
    }
    return nil;
}

- (ShopObject *)getShopObject:(NSString *)usercode{
     NSString *sql = [NSString stringWithFormat:@"select  a2.* from s_user a1 join s_shopid a2 on a1.shopid = a2.shopid where usercode = '%@'",usercode];
     FMResultSet *rs = [db_ executeQuery:sql];
     while ([rs next]) {
     ShopObject *obj = [[ShopObject alloc] init];
     obj.shopName = [rs stringForColumn:@"shopName"];
     obj.shopID = [rs stringForColumn:@"shopid"];
     obj.bOrder = [rs stringForColumn:@"ismodify"];
     return obj;
     }
    return nil;
}

- (NSString *)getUserCode:(NSString *)u_id{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where biurl = '%@'",u_id];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [rs stringForColumn:@"usercode"];
    }
    return @"";
}

- (NSArray *)getShopObjects:(NSString *)usercode{
    /*
    NSString *sql = [NSString stringWithFormat:@"select  a2.* from s_user a1 join s_shopid a2 on a1.shopid = a2.shopid where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ShopObject *obj = [[ShopObject alloc] init];
        obj.shopName = [rs stringForColumn:@"shopName"];
        obj.shopID = [rs stringForColumn:@"shopid"];
        obj.bOrder = [rs stringForColumn:@"ismodify"];
        return obj;
    }
     */
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ShopObject *obj = [[ShopObject alloc] init];
        obj.shopName = [rs stringForColumn:@"shopName"];
        obj.shopID = [rs stringForColumn:@"shopid"];
        obj.bOrder = [rs stringForColumn:@"bOrder"];
        obj.bCheck = [[rs stringForColumn:@"bCheck"] intValue];
        [array addObject:obj];
    }
    return array;
}

- (BOOL)addUser:(NSString *)usercode name:(NSString *)username password:(NSString *)password u_id:(NSString *)u_id shopid:(NSString *)shopID shopname:(NSString *)shopname{
    NSString *sql = [NSString stringWithFormat:@"insert into s_user('n_id','usercode','username','shopid','password','u_id') values(0,'%@','%@','%@','%@','%@')",usercode,username,shopID,password,u_id];
    BOOL res = [self excuteSQL:sql];
    if (!res) {
        sql = [NSString stringWithFormat:@"update s_user set username = '%@', shopid = '%@', password = '%@',u_id = '%@' WHERE usercode = '%@'",username,shopID,password,u_id,usercode];
        res = [self excuteSQL:sql];
        if (!res) {
            return res;
        }
    }

    NSString *shop = [NSString stringWithFormat:@"insert into s_shopid('shopid','shopName') values('%@','%@')",shopID,shopname];
    res = [self excuteSQL:shop];
    
    return res;
}

//- (NSString *)getFavoritePath{
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *dir = [paths objectAtIndex:0];
//    NSString *filePath = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"favorite_%@.plist",userObject_.userCode]];
//    
//    return filePath;
//}

//获取用户收藏的产品列表
- (NSArray *)getFavoriteProducts:(NSArray*)filters Shopid:(NSString*)shopid{

    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat: @"select a2.* from my_favorite  a1 join v_g_spdm a2 on a1.code = a2.code and a1.colorid = a2.colorid where a1.usercode = '%@' and a1.type = '0'",
    [[DataManager sharedManager] getUserObject].userCode];
    
//    if (shopid) {
//        sql = [sql stringByAppendingFormat:@" and a1.shopid = '%@'",shopid ];
//    }
    
    NSString* condition = @" ";
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and %@ = '%@'",key.columnname,key.keyName ];
        }
    }
    
    sql = [sql stringByAppendingString:condition];
    sql = [sql stringByAppendingFormat:@" order by a1.starlevel desc"];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        ProductObject *obj = [self createProductObject:rs];
        [array addObject:obj];
    }
    
    return array;
}

-(NSMutableDictionary *)getFavoriteCount:(NSString *)shopid all:(NSString *)allname
{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSString *sql = [NSString stringWithFormat: @"select count(1) as icount,a3.c_xilmc from my_favorite a1 left join  g_spdm a2 on a1.code = a2.code left join r_xilie a3 on a2.c_xilbh=a3.c_xilbh where a1.usercode = '%@'  group by a3.c_xilmc ",[[DataManager sharedManager] getUserObject].userCode];

    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
//        [array addObject:[rs resultDictionary]];
        [dic setObject:[[rs resultDictionary] objectForKey:@"icount"] forKey:[[rs resultDictionary] objectForKey:@"c_xilmc"]];
    }
    
    
    sql = [NSString stringWithFormat: @"select count(1) as icount,' ' as c_xilmc from my_favorite where usercode = '%@'",[[DataManager sharedManager] getUserObject].userCode];
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        [dic setObject:[[rs resultDictionary] objectForKey:@"icount"] forKey:allname];
    }
    
    return dic;
}
//设置产品为收藏
- (void)setAsFavorite:(ProductObject *)product withStar:(int)star Shopid:(NSString*)shopid type:(NSString *)type{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:shopid forKey:@"shopid"];
    [dict setObject:[[DataManager sharedManager] getUserObject].userCode forKey:@"usercode"];
    [dict setObject: product.pCode forKey:@"code"];
    [dict setObject: product.pColorCode forKey:@"colorid"];
    [dict setObject: [NSString stringWithFormat:@"%d",star] forKey:@"starlevel"];
    [dict setObject:type forKey:@"type"];
    
    NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
    NSArray *arr = [NSArray arrayWithObjects:dict, nil];
    [self insertValueToTable:@" my_favorite " withArray:arr byKey:keys];
    
}

- (void)cancelAsFavorite:(ProductObject *)product Shopid:(NSString*)shopid{
    
    NSString *sql = [NSString stringWithFormat:@"delete from my_favorite where code = '%@' and colorid = '%@' and usercode= '%@'",
                     product.pCode,product.pColorCode,[[DataManager sharedManager] getUserObject].userCode];
//    if(shopid) {
//        sql = [sql stringByAppendingFormat:@" and shopid = '%@'",shopid ];
//    }
    
    [self excuteSQL:sql];
    
}

//产品是否被收藏
- (int)productIsFavorite:(ProductObject *)product Shopid:(NSString*)shopid{
    NSString *sql = [NSString stringWithFormat: @"select starlevel from my_favorite where usercode = '%@' and code = '%@' and colorid = '%@' ",
                     [[DataManager sharedManager] getUserObject].userCode,product.pCode,product.pColorCode];
    
//    if (shopid) {
//        sql = [sql stringByAppendingFormat:@" and shopid = '%@'",shopid ];
//    }
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [[rs stringForColumn:@"starlevel"]intValue];
    }
    return 0;
}
//获取用户收藏的配装列表
- (NSArray *)getsuitFavoriteProducts:(NSArray *)filters Shopid:(NSString *)shopid{
    
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat: @"select distinct a2.scripno,a2.iodate,a2.n_id,a2.c_miaos,a2.pic_path,a2.c_mingc from my_favorite a1,g_billm_Assembling a2,g_billd_Assembling a3,v_g_spdm a4 where a1.type = '1' and a1.code = a2.scripno and a1.usercode = '%@' and a2.scripno = a3.scripno and a3.code = a4.code",
                     [[DataManager sharedManager] getUserObject].userCode];
    
//    if (shopid) {
//        sql = [sql stringByAppendingFormat:@" and a1.shopid = '%@'",shopid ];
//    }

    NSString* condition = @" ";
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and a4.%@ = '%@'",key.columnname,key.keyName ];
        }
    }
    
    sql = [sql stringByAppendingString:condition];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        SuitObject *suit = [[SuitObject alloc] init];
        
        suit.scriptNo = [rs stringForColumn:@"scripno"];
//        suit.ioDate = [rs stringForColumn:@"iodate"];
        suit.n_id = [rs intForColumn:@"n_id"];
        suit.c_miaos = [rs stringForColumn:@"c_miaos"];
        suit.pic_path = [rs stringForColumn:@"pic_path"];
        suit.c_mingc = [rs stringForColumn:@"c_mingc"];
        suit.theme = [rs stringForColumn:@"theme"];
        suit.recommend = [rs stringForColumn:@"recommend"];
        
        sql = [NSString stringWithFormat:@"select * from g_billd_Assembling where scripno = '%@' and flag = 1",suit.scriptNo];
        
        NSMutableArray *component = [[NSMutableArray alloc] init];
        FMResultSet *subRes = [db_ executeQuery:sql];
        while ([subRes next]) {
            SubSuitObject *obj = [[SubSuitObject alloc] init];
            
            obj.subSuitType = [subRes stringForColumn:@"type"];
            obj.productCode = [subRes stringForColumn:@"code"];
            obj.colorid = [subRes stringForColumn:@"colorid"];
            obj.productImage = [subRes stringForColumn:@"c_url"];
            obj.scriptNo = [rs stringForColumn:@"scripno"];
            
            [component addObject:obj];
        }
        
        suit.components = component;
        
        [array addObject:suit];
    }
    
    return array;
}

//设置配装为收藏
- (void)setAssuitFavorite:(SuitObject *)suit withStar:(int)star Shopid:(NSString *)shopid type:(NSString *)type{
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:shopid forKey:@"shopid"];
    [dict setObject:[[DataManager sharedManager] getUserObject].userCode forKey:@"usercode"];
    [dict setObject: suit.scriptNo forKey:@"code"];
   // [dict setObject: product.pColorCode forKey:@"colorid"];
    [dict setObject: [NSString stringWithFormat:@"%d",star] forKey:@"starlevel"];
    [dict setObject:type forKey:@"type"];
    
    NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
    NSArray *arr = [NSArray arrayWithObjects:dict, nil];
    [self insertValueToTable:@" my_favorite " withArray:arr byKey:keys];
    
}

- (void)cancelAssuitFavorite:(SuitObject *)suit Shopid:(NSString *)shopid{
    
    NSString *sql = [NSString stringWithFormat:@"delete from my_favorite where code = '%@' and usercode= '%@'",
                     suit.scriptNo,[[DataManager sharedManager] getUserObject].userCode];
//    if(shopid) {
//        sql = [sql stringByAppendingFormat:@" and shopid = '%@'",shopid ];
//    }
    
    [self excuteSQL:sql];
    
}
//产品是否被收藏
- (int)productIssuitFavorite:(SuitObject *)suit Shopid:(NSString *)shopid{
    NSString *sql = [NSString stringWithFormat: @"select starlevel from my_favorite where usercode = '%@' and code = '%@' ",
                     [[DataManager sharedManager] getUserObject].userCode,suit.scriptNo];
    
//    if (shopid) {
//        sql = [sql stringByAppendingFormat:@" and shopid = '%@'",shopid ];
//    }
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [[rs stringForColumn:@"starlevel"]intValue];
    }
    return 0;
}


- (void)deleteTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"delete from %@",tablename];
    [self excuteSQL:sql];
}


- (void)deleteTableByShop:(NSString *)tablename shop:(NSString *)shopid{
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where shopid = '%@'",tablename,shopid];
    [self excuteSQL:sql];
}

- (NSArray *)getSuitSerialArray{
    
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *sql = [NSString stringWithFormat: @"select distinct theme from g_billm_Assembling where ifnull(theme,'')<>''"];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        [array addObject:[rs stringForColumn:@"theme"]];
    }
    return array;
}


//刷新产品表，与服务器更新
- (void)refreshProductTable:(DMCompletion)completion{

    [[WebServiceManager sharedManager] refreshProductInfo:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"g_spdm"];
            [self insertValueToTable:@"g_spdm" withArray:products byKey:nil];

        }
        completion(nil);
    }];
}

- (void)refreshProductColoridTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshProductColorid:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"g_spdmdetail"];
            [self insertValueToTable:@"g_spdmdetail" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshProductPictureTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshProductPicture:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"g_spdm_img"];
            [self insertValueToTable:@"g_spdm_img" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshColortblTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshColortbl:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_colortbl"];
            [self insertValueToTable:@"r_colortbl" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshXilieTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshXilie:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_xilie"];
            [self insertValueToTable:@"r_xilie" withArray:products byKey:nil];
        }

        completion(nil);
    }];
}

- (void)refreshKuansTable:(DMCompletion)completion{

    [[WebServiceManager sharedManager] refreshKuans:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_kuans"];
            [self insertValueToTable:@"r_kuans" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshKuanxTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshKuanx:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_kuanx"];
            [self insertValueToTable:@"r_kuanx" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshXiaoxlTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshXiaoxl:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_xiaoxl"];
            [self insertValueToTable:@"r_xiaoxl" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshNianfTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshNianf:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_nianf"];
            [self insertValueToTable:@"r_nianf" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshJijieTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshJijie:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_jijie"];
            [self insertValueToTable:@"r_jijie" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshPingpTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshPingp:0 completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_pingp"];
            [self insertValueToTable:@"r_pingp" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshSpdmStatusTimeTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshSpdmStatusTimeInfo:nil completion:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"spdmstatustime"];
            [self insertValueToTable:@"spdmstatustime" withArray:products byKey:nil];
            [self updateProductstatus:products];
        }
        
        completion(nil);
    }];
}


- (void)refreshSaleSegmentTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshSaleSegment:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"r_dictvalue"];
            [self insertValueToTable:@"r_dictvalue" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}



- (void)refreshSpdmSizeTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshSizeInfo:^(NSArray *products){
        if (products.count>0) {
            [self deleteTable:@"spdmsize"];
            [self insertValueToTable:@"spdmsize" withArray:products byKey:nil];
        }
        
        completion(nil);
    }];
}

- (long)getOrderLastTime{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    NSString *sql = [NSString stringWithFormat:@"select max(MaxSynID)  as max_time from g_meeting where  shopid = '%@'",shopobj.shopID];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *d = [rs stringForColumn:@"max_time"];
        return [d longLongValue];
    }
    
    long d = 0;
    
    return d ;
}


- (NSString*)getSpdmSizeTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from spdmsize where d_id = '%@'",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0";
}

- (NSString*)getOrderLastTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from g_meeting where MaxSynID = '%@'",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0" ;
}

- (NSDate*)getSpdmSizeLastTime{
    NSString *sql = [NSString stringWithFormat:@"select max(d_id)  as max_time from spdmsize "];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *s = [rs stringForColumn:@"max_time"];
        NSDate* d = [dateFormatter dateFromString:s];
        return d;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *d = [dateFormatter dateFromString:@"1900-01-01 00:00:00"];
    return d ;
}


- (long)getg_SizeLastTime{
    NSString *sql = [NSString stringWithFormat:@"select max(MaxSynID)  as max_time from g_size "];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *d = [rs stringForColumn:@"max_time"];
        return [d longLongValue];
    }
    
    long d = 0;
    
    return d ;
}

- (NSString*)getSpdmSizeLastTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from spdmsize where d_id = '%@'",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0" ;
}


- (void)updateOrderByShopID:(NSString *)shopid completion:(DMCompletion)completion{
    long lastd = [self getOrderLastTime];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getOrderTableRequest:lastd];
        NSLog(@"update order:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        orderUpdates_ = array;
        //        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        //        NSString *formattedString = [dateFormatter stringFromDate:lastd];
        //        int dbcount = [[self getOrderLastTimeCount:formattedString]intValue];
        //
        //        if (array.count!=dbcount) {
        //            orderUpdates_ = array;
        //        }
    }
    else
    {
        [[WebServiceManager sharedManager] refreshOrderTable:lastd completion:^(NSArray *array){
            for (NSDictionary *dic in array) {
                NSString *sql = [NSString stringWithFormat:@"delete from g_meeting where code = '%@' and colorid = '%@' and shopid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"shopid"]];
                [self excuteSQL:sql];
            }
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize",@"shopid",@"usercode", nil];
            [self insertValueToTable:@"g_meeting" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

- (void)updateOrder:(DMCompletion)completion{
    long lastd = [self getOrderLastTime];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getOrderTableRequest:lastd];
        NSLog(@"update order:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        orderUpdates_ = array;
        //        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        //        NSString *formattedString = [dateFormatter stringFromDate:lastd];
        //        int dbcount = [[self getOrderLastTimeCount:formattedString]intValue];
        //
        //        if (array.count!=dbcount) {
        //            orderUpdates_ = array;
        //        }
    }
    else
    {
        [[WebServiceManager sharedManager] refreshOrderTable:lastd completion:^(NSArray *array){
//            for (NSDictionary *dic in array) {
//                NSString *sql = [NSString stringWithFormat:@"delete from g_meeting where code = '%@' and colorid = '%@' and shopid = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"shopid"]];
//                [self excuteSQL:sql];
//            }
            
            [self deleteTable:@"g_meeting_dl"];
            [self insertValueToTable:@"g_meeting_dl" withArray:array byKey:nil];
            
            NSString *sql = [NSString stringWithFormat:@"delete from g_meeting where shopid||'-'||code||'-'||colorid in (select  shopid||'-'||code||'-'||colorid from g_meeting_dl) "];
            if(![self excuteSQL:sql]){
                NSLog(@"%@",sql);
            }
            
            sql = [NSString stringWithFormat:@" insert into g_meeting (shopid,code,colorid,xsize ,amount,MaxSynID,d_upid) select shopid,code,colorid,xsize ,amount,MaxSynID,d_upid from g_meeting_dl"];
            if (![self excuteSQL:sql]) {
                NSLog(@"%@",sql);
            }
//            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize",@"shopid",
//                             nil];
//            [self insertValueToTable:@"g_meeting" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

- (void)updateSpdmSize:(DMCompletion)completion{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSDate *lastd = [self getSpdmSizeLastTime];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getSpdmSizeTableRequest:lastd];
        NSLog(@"update spdm size:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *formattedString = [dateFormatter stringFromDate:lastd];
        int dbcount = [[self getSpdmSizeLastTimeCount:formattedString]intValue];
        
        NSDictionary *d = [array objectAtIndex:0];
        
        if (array.count!=dbcount && d.allKeys.count > 0) {
            spdmorderUpdates_ = array;
        }
        
    }
    else
    {
        [[WebServiceManager sharedManager] refreshSpdmSizeTable:lastd completion:^(NSArray *array){
            for (NSDictionary *dic in array) {
                NSString *sql = [NSString stringWithFormat:@"delete from spdmsize where code = '%@' and colorid = '%@' and xsize = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"xsize"]];
                [self excuteSQL:sql];
            }
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize", nil];
            [self insertValueToTable:@"spdmsize" withArray:array byKey:keys];
            completion(nil);
        }];
    }
    /*
     NSDate *lastd = [self getSpdmSizeLastTime];
     //NSDate* d = [NSDate dateWithTimeIntervalSince1970:0];
     if (completion==nil) {
     RFRequest *r = [[WebServiceManager sharedManager] getSpdmSizeTableRequest:lastd];
     NSLog(@"update order:%@",r.URL);
     NSString *s = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
     NSArray *array = [s objectFromJSONString];
     
     if (array.count) {
     NSDictionary *d = [array objectAtIndex:0];
     if (d.allKeys.count>0) {
     
     NSDictionary* lastRd = [array objectAtIndex:array.count-1];
     
     NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
     dateFormatter1.dateFormat = @"yyyy-MM-dd HH:mm:ss";
     NSDate *lastRddate = [dateFormatter1 dateFromString:[lastRd objectForKey:@"d_id"]];
     
     if ([lastRddate compare:lastd] != NSOrderedSame ) {
     spdmorderUpdates_ = array;
     }
     else{
     
     int count = 0;
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
     NSString* strd = [dateFormatter stringFromDate:lastd ];
     //判断和最晚日期的记录数是否相同
     
     for (NSDictionary* dict in array){
     
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
     NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"d_id"]];
     if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
     count++;
     }
     }
     
     int dbcount = [[self getSpdmSizeLastTimeCount:strd]intValue];
     
     if (count!=dbcount) {
     spdmorderUpdates_ = array;
     
     }
     }
     
     }
     
     }
     
     }else{
     [[WebServiceManager sharedManager] refreshSpdmSizeTable:lastd completion:^(NSArray *array){
     for (NSDictionary *dic in array) {
     NSString *sql = [NSString stringWithFormat:@"delete from spdmsize where code = '%@' and colorid = '%@' and xsize = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"xsize"]];
     [self excuteSQL:sql];
     }
     
     NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize", nil];
     [self insertValueToTable:@"spdmsize" withArray:array byKey:keys];
     completion(nil);
     }];
     }
     */
}

- (void)updateg_Size:(DMCompletion)completion{
    long lastd = [self getg_SizeLastTime];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getg_SizeTableRequest:lastd];
        NSLog(@"update g_size:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        
        NSDictionary *d = [array objectAtIndex:0];
        if (d.allKeys.count==0) {
            return;
        }
        
        g_sizeUpdates_ = array;
        
    }
    else
    {
        [[WebServiceManager sharedManager] refreshg_SizeTable:lastd completion:^(NSArray *array){
            for (NSDictionary *dic in array) {
                NSString *sql = [NSString stringWithFormat:@"delete from g_size where code = '%@'",[dic objectForKey:@"code"]];
                [self excuteSQL:sql];
            }
            
            NSArray *keys = [NSArray arrayWithObjects:@"code", nil];
            [self insertValueToTable:@"g_size" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

-(void)updateTip:(DMCompletion)completion
{
    NSString *time = [self getTipsLastTime];
//    NSDate *lastd1 = [lastd dateByAddingTimeInterval:1];
//    NSString *time = [formatter stringFromDate:lastd];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getTipRequest:userObject_.userCode date:time];
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        NSDictionary *dic = [array objectAtIndex:0];
        if (dic.allKeys.count>0) {
            NSMutableArray *res = [NSMutableArray array];
            for ( NSDictionary *d in array ) {

                NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                //[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
                
                NSString *s = [d objectForKey:@"d_id"];
                NSDate *date1 = [formatter dateFromString:s];
                NSDate *date2 = [formatter dateFromString:time];
                if (date2==nil || [date1 compare:date2]==NSOrderedDescending) {
                    [res addObject:d];
                }
                
            }
            
            [self setTipsarray:res];
        }
    }
    else
    {
        [[WebServiceManager sharedManager] gettip:userObject_.userCode time:time completion:^(NSArray *array){
            NSArray *keys = [NSArray arrayWithObjects:@"title",@"content",@"d_id", nil];
            [self insertValueToTable:@"tips" withArray:array byKey:keys];
        }];
    }
}

- (void)updateSpdmOrder:(DMCompletion)completion{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSDate *lastd = [self getSpdmSizeLastTime];
    
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getSpdmSizeTableRequest:lastd];
        NSLog(@"update spdm size:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count==0) {
            return;
        }
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *formattedString = [dateFormatter stringFromDate:lastd];
        int dbcount = [[self getSpdmSizeLastTimeCount:formattedString]intValue];
        
        NSDictionary *d = [array objectAtIndex:0];
        
        if (array.count!=dbcount && d.allKeys.count > 0) {
            spdmorderUpdates_ = array;
        }
        
    }
    else
    {
        [[WebServiceManager sharedManager] refreshSpdmSizeTable:lastd completion:^(NSArray *array){
            for (NSDictionary *dic in array) {
                NSString *sql = [NSString stringWithFormat:@"delete from spdmsize where code = '%@' and colorid = '%@' and xsize = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"xsize"]];
                [self excuteSQL:sql];
            }
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize", nil];
            [self insertValueToTable:@"spdmsize" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

- (NSDate*)getSuitLastTime{
    NSString *sql = @"select max(d_id)  as max_time from g_billm_assembling ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate* d = [dateFormatter dateFromString: [rs stringForColumn:@"max_time"]];
        return d;
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *d = [dateFormatter dateFromString:@"1900-01-01 00:00:00"];
    return d ;
}


- (NSString*)getSuitLastTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from g_billm_assembling where d_id = '%@' ",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0" ;
}


- (void)updateSuitPm:(DMCompletion)completion{
    
    NSDate * lastd = [self getSuitLastTime];
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getPMTableRequest:lastd];
        NSLog(@"update suit:%@",r.URL);
        NSString *s = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [s objectFromJSONString];
        if (array.count) {
            NSDictionary *d = [array objectAtIndex:0];
            if (d.allKeys.count>0) {
                
                int count = 0;
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                NSString* strd = [dateFormatter stringFromDate:lastd ];
                //判断和最晚日期的记录数是否相同
                for (NSDictionary* dict in array){
                    
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                    NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"d_id"]];
                    if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
                        count++;
                    }
                }
                
                
                int dbcount = [[self getSuitLastTimeCount:strd]intValue];
                
                if (count!=dbcount) {
                    suitUpdates_ = array;
                    
                }
            }
            
        }
    }else{
        [[WebServiceManager sharedManager] refreshPMTable:lastd completion:^(NSArray *array){
            
            NSArray *keys = [NSArray arrayWithObjects:@"scripno", nil];
            [self insertValueToTable:@"g_billm_Assembling" withArray:array byKey:keys];
            for (NSDictionary *dic in array) {
                NSString *sql = [NSString stringWithFormat:@"delete from g_billd_Assembling where scripno = '%@'",[dic objectForKey:@"scripno"]];
                [self excuteSQL:sql];
            }
            for ( NSDictionary *dic in array ) {
                [[WebServiceManager sharedManager] refreshPDTable:[dic objectForKey:@"scripno"] completion:^(NSArray *array){
                    NSArray *keys = [NSArray arrayWithObjects:@"n_id", nil];
                    [self insertValueToTable:@"g_billd_Assembling" withArray:array byKey:keys];
                    
                }];
            }
            
            completion(array);
        }];
    }
    
}


- (long)getProductLastTime{
    NSString *sql = @"select max(MaxSynID)  as max_time from g_spdm ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *d = [rs stringForColumn:@"max_time"];
        return [d longLongValue];
    }
    
    long d = 0;
    return d;
}

- (long)getProductColoridLastTime{
    NSString *sql = @"select max(MaxSynID)  as max_time from g_spdmdetail ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *d = [rs stringForColumn:@"max_time"];
        return [d longLongValue];
    }
    
    long d = 0;
    return d;
}

- (long)getProductPictureLastTime{
    NSString *sql = @"select max(MaxSynID)  as max_time from g_spdm_img ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *d = [rs stringForColumn:@"max_time"];
        return [d longLongValue];
    }
    
    long d = 0;
    return d;
}

- (NSString*)getProductLastTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from v_g_spdm where MaxSynID = '%@' ",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0" ;
}

- (NSDate*)getSpdmStatusTimeLastTime{
    NSString *sql = @"select max(d_update_prod)  as max_time from spdmstatustime ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate* d = [dateFormatter dateFromString: [rs stringForColumn:@"max_time"]];
        return d;
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *d = [dateFormatter dateFromString:@"1900-01-01 00:00:00"];
    return d ;
}

- (NSString*)getSpdmStatusTimeLastTimeCount:(NSString*) strd{
    NSString *sql = [NSString stringWithFormat: @"select count(*)  as cnt from spdmstatustime where d_update_prod = '%@' ",strd];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return  [rs stringForColumn:@"cnt"];
        
    }
    
    return @"0" ;
}

- (NSString*)getTipsLastTime{
    NSString *sql = @"select max(d_id)  as max_time from tips ";
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
//        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//        NSDate* d = [dateFormatter dateFromString: [rs stringForColumn:@"max_time"]];
//        return d;
        return [rs stringForColumn:@"max_time"];
    }
    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//    NSDate *d = [dateFormatter dateFromString:@"1900-01-01 00:00:00"];
    return @"1900-01-01 00:00:00" ;
}

- (BOOL)hasUpdate{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    NSString *path = [cacheDir stringByAppendingPathComponent:@"updateLog.txt"];
    
    
    NSString *s = [NSString stringWithContentsOfFile:path
                                            encoding:NSUTF8StringEncoding error:nil];
    if (!s) {
        s = @"";
    }
    
    
    s = [s stringByAppendingFormat:@"\n--------------\n"];
    
    if (productUpdates_) {
        s = [s stringByAppendingString:@"product has update\n"];
    }
    
    if (productColorids_) {
        s = [s stringByAppendingString:@"productcolorid has update\n"];
    }
    
    if (productPictures_) {
        s = [s stringByAppendingString:@"productpicture has update\n"];
    }
    
    if (suitUpdates_) {
        s = [s stringByAppendingString:@"suit has update\n"];
    }
    
    //    if (orderUpdates_) {
    //        return YES;
    //    }
    
//    if (spdmorderUpdates_) {
//        s = [s stringByAppendingString:@"size has update\n"];
//    }
    
    if (spdmstatustimeUpdates_) {
        s = [s stringByAppendingString:@"spdm status has update\n"];
    }
    
    if (g_sizeUpdates_) {
        s = [s stringByAppendingString:@"g_size has update\n"];
    }
    
    s = [s stringByAppendingFormat:@"%@\n--------------\n",[NSDate date]];
    
    [s writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (productUpdates_) {
        NSLog(@"product has update");
        return YES;
    }
    
    if (productColorids_) {
        NSLog(@"productcolorid has update");
        return YES;
    }
    
    if (g_sizeUpdates_) {
        return YES;
    }
    
    if (productPictures_) {
        NSLog(@"productpicture has update");
        return YES;
    }
    
    if (suitUpdates_) {
        NSLog(@"suit has update");
        return YES;
    }
    
    //    if (orderUpdates_) {
    //        return YES;
    //    }
    
//    if (spdmorderUpdates_) {
//        NSLog(@"size has update");
//        return YES;
//    }
    
    if (spdmstatustimeUpdates_) {
        NSLog(@"spdm status has update");
        return YES;
    }
    
    return NO;
}
- (BOOL)hasTipUpdate{
    if (TipUpdates_) {
        return YES;
    }
    return NO;
}
- (void)performUpdate{
    if (productUpdates_) {
        [db_ beginTransaction];
        for (NSDictionary *dic in productUpdates_) {
            NSString *sql = [NSString stringWithFormat:@"delete from g_spdm where code = '%@'",[dic objectForKey:@"code"]];
            [self excuteSQL:sql];
        }
        [db_ commit];
        NSArray *keys = [NSArray arrayWithObjects:@"code", nil];
        [self insertValueToTable:@"g_spdm" withArray:productUpdates_ byKey:keys];
        
        productUpdates_ = nil;
    }
    
    if (productColorids_) {
        [db_ beginTransaction];
        for (NSDictionary *dic in productColorids_) {
            NSString *sql = [NSString stringWithFormat:@"delete from g_spdmdetail where code = '%@' and colorid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
            [self excuteSQL:sql];
        }
        [db_ commit];
        NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
        [self insertValueToTable:@"g_spdmdetail" withArray:productColorids_ byKey:keys];
        
        productColorids_ = nil;
    }
    
    if (productPictures_) {
        [db_ beginTransaction];
        for (NSDictionary *dic in productPictures_) {
            NSString *sql = [NSString stringWithFormat:@"delete from g_spdm_img where code = '%@' and colorid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
            [self excuteSQL:sql];
        }
        [db_ commit];
        NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
        [self insertValueToTable:@"g_spdm_img" withArray:productPictures_ byKey:keys];
        
        productPictures_ = nil;
    }
    
    if (spdmstatustimeUpdates_) {
        [db_ beginTransaction];
        for (NSDictionary *dic in spdmstatustimeUpdates_) {
            NSString *sql = [NSString stringWithFormat:@"delete from spdmstatustime where code = '%@' and colorid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
            [self excuteSQL:sql];
        }
        [db_ commit];
        NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
        [self insertValueToTable:@"spdmstatustime" withArray:spdmstatustimeUpdates_ byKey:keys];
        [self updateProductstatus:spdmstatustimeUpdates_];
        
        spdmstatustimeUpdates_ = nil;
    }
    
    if (suitUpdates_) {
        NSArray *keys = [NSArray arrayWithObjects:@"scripno", nil];
        [self insertValueToTable:@"g_billm_Assembling" withArray:suitUpdates_ byKey:keys];
        for (NSDictionary *dic in suitUpdates_) {
            NSString *sql = [NSString stringWithFormat:@"delete from g_billd_Assembling where scripno = '%@'",[dic objectForKey:@"scripno"]];
            [self excuteSQL:sql];
        }
        for (NSDictionary *dic in suitUpdates_) {
            RFRequest *r = [[WebServiceManager sharedManager] getPDTableRequest:[dic objectForKey:@"scripno"]];
            NSString *s = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
            NSArray *array = [s objectFromJSONString];
            NSArray *keys = [NSArray arrayWithObjects:@"n_id", nil];
            [self insertValueToTable:@"g_billd_Assembling" withArray:array byKey:keys];
        }
        
        suitUpdates_ = nil;
    }
    
//    if (orderUpdates_) {
//        NSMutableArray *array = [[NSMutableArray alloc]init];
//        for (NSDictionary *dic in orderUpdates_) {
//            if ([dic objectForKey:@"usercode"]==nil) {
//                continue;
//            }
//            [array addObject:dic];
//            NSString *sql = [NSString stringWithFormat:@"delete from g_meeting where code = '%@' and colorid = '%@' and shopid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"shopid"]];
//            [self excuteSQL:sql];
//            
//        }
//        
//        NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize",@"shopid", nil];
//        [self insertValueToTable:@"g_meeting" withArray:array byKey:keys];
//        
//        array = nil;
//        orderUpdates_ = nil;
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh" object:nil];
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh1" object:nil];
//    }
    
    if (spdmorderUpdates_) {
        for (NSDictionary *dic in spdmorderUpdates_) {
            NSString *sql = [NSString stringWithFormat:@"delete from spdmsize where code = '%@' and colorid = '%@' and xsize = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"],[dic objectForKey:@"xsize"]];
            [self excuteSQL:sql];
        }
        NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize", nil];
        [self insertValueToTable:@"spdmsize" withArray:spdmorderUpdates_ byKey:keys];
        
        spdmorderUpdates_ = nil;
    }
    
    if (g_sizeUpdates_) {
        [db_ beginTransaction];
        for (NSDictionary *dic in g_sizeUpdates_) {
            NSString *sql = [NSString stringWithFormat:@"delete from g_size where code = '%@'",[dic objectForKey:@"code"]];
            [self excuteSQL:sql];
        }
        [db_ commit];
        NSArray *keys = [NSArray arrayWithObjects:@"code", nil];
        [self insertValueToTable:@"g_size" withArray:g_sizeUpdates_ byKey:keys];
        
        g_sizeUpdates_ = nil;
    }
    
    [WaitTooles removeHUD];
}
-(void)performTipUpdate
{
    if (TipUpdates_) {
        NSArray *keys = [NSArray arrayWithObjects:@"title",@"content",@"d_id", nil];
        [self insertValueToTable:@"tips" withArray:TipUpdates_ byKey:keys];
        
        TipUpdates_ = nil;
    }
}

- (void)updateProductTable:(WebServiceCompletion)completion{
    
    long lastd = [self getProductLastTime];
    //    lastd = [NSDate dateWithTimeInterval:1 sinceDate:lastd];
    // NSDate* lastd = [NSDate dateWithTimeIntervalSince1970:0];
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getProductInfoRequest:lastd];
        NSLog(@"update product:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count) {
            NSDictionary *d = [array objectAtIndex:0];
            if (d.allKeys.count>0) {
                productUpdates_ = array;
                //                int count = 0;
                //                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                NSString* strd = [dateFormatter stringFromDate:lastd ];
                //
                //                //判断和最晚日期的记录数是否相同
                //                for (NSDictionary* dict in array){
                //
                //                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                    NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"MaxSynID"]];
                //                    if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
                //                        count++;
                //                    }
                //                }
                //
                //                int dbcount = [[self getProductLastTimeCount:strd]intValue];
                //
                //                if (count!=dbcount) {
                //                    productUpdates_ = array;
                //                }
                
            }
            
        }
        
    }else{
        [[WebServiceManager sharedManager] refreshProductInfo:lastd completion:^(NSArray *array){
            
            NSArray *keys = [NSArray arrayWithObjects:@"code", nil];
            [self insertValueToTable:@"g_spdm" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

- (void)updateProductColoridTable:(WebServiceCompletion)completion{
    
    long lastd = [self getProductColoridLastTime];
    //    lastd = [NSDate dateWithTimeInterval:1 sinceDate:lastd];
    // NSDate* lastd = [NSDate dateWithTimeIntervalSince1970:0];
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getProductColoridRequest:lastd];
        NSLog(@"update product:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count) {
            NSDictionary *d = [array objectAtIndex:0];
            if (d.allKeys.count>0) {
                productColorids_ = array;
                //
                //                int count = 0;
                //                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                NSString* strd = [dateFormatter stringFromDate:lastd ];
                //
                //                //判断和最晚日期的记录数是否相同
                //                for (NSDictionary* dict in array){
                //
                //                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                    NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"MaxSynID"]];
                //                    if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
                //                        count++;
                //                    }
                //                }
                //
                //                int dbcount = [[self getProductLastTimeCount:strd]intValue];
                //
                //                if (count!=dbcount) {
                //                    productColorids_ = array;
                //                }
                //
            }
            
        }
        
    }else{
        [[WebServiceManager sharedManager] refreshProductColorid:lastd completion:^(NSArray *array){
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
            [self insertValueToTable:@"g_spdmdetail" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}

- (void)updateProductPictureTable:(WebServiceCompletion)completion{
    
    long lastd = [self getProductPictureLastTime];
    //    lastd = [NSDate dateWithTimeInterval:1 sinceDate:lastd];
    // NSDate* lastd = [NSDate dateWithTimeIntervalSince1970:0];
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getProductPictureRequest:lastd];
        NSLog(@"update product:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count) {
            NSDictionary *d = [array objectAtIndex:0];
            if (d.allKeys.count>0) {
                productPictures_ = array;
                //                int count = 0;
                //                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                NSString* strd = [dateFormatter stringFromDate:lastd ];
                //
                //                //判断和最晚日期的记录数是否相同
                //                for (NSDictionary* dict in array){
                //
                //                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                //                    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                //                    NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"MaxSynID"]];
                //                    if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
                //                        count++;
                //                    }
                //                }
                //
                //                int dbcount = [[self getProductLastTimeCount:strd]intValue];
                //
                //                if (count!=dbcount) {
                //                    productPictures_ = array;
                //                }
                
            }
            
        }
        
    }else{
        [[WebServiceManager sharedManager] refreshProductPicture:lastd completion:^(NSArray *array){
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
            [self insertValueToTable:@"g_spdm_img" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}


- (void)updateSpdmStatusTimeTable:(DMCompletion)completion{
    
    NSDate *lastd = [self getSpdmStatusTimeLastTime];
    //    lastd = [NSDate dateWithTimeInterval:1 sinceDate:lastd];
    // NSDate* lastd = [NSDate dateWithTimeIntervalSince1970:0];
    if (completion==nil) {
        RFRequest *r = [[WebServiceManager sharedManager] getSpdmStatusTimeInfoRequest:lastd];
        NSLog(@"update spdm status:%@",r.URL);
        NSString *res = [NSString stringWithContentsOfURL:r.URL encoding:NSUTF8StringEncoding error:nil];
        NSArray *array = [res objectFromJSONString];
        if (array.count) {
            NSDictionary *d = [array objectAtIndex:0];
            if (d.allKeys.count>0) {
                
                int count = 0;
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                NSString* strd = [dateFormatter stringFromDate:lastd ];
                
                //判断和最晚日期的记录数是否相同
                for (NSDictionary* dict in array){
                    
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
                    NSDate *d = [dateFormatter dateFromString:[dict objectForKey:@"d_update_prod"]];
                    if ([d compare:lastd]==NSOrderedDescending|| [d compare:lastd]==NSOrderedSame) {
                        count++;
                    }
                }
                
                int dbcount = [[self getSpdmStatusTimeLastTimeCount:strd]intValue];
                
                if (count!=dbcount) {
                    spdmstatustimeUpdates_ = array;
                }
                
            }
            
        }
        
    }else{
        [[WebServiceManager sharedManager] refreshSpdmStatusTimeInfo:lastd completion:^(NSArray *array){
            
            NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid", nil];
            [self insertValueToTable:@"spdmstatustime" withArray:array byKey:keys];
            completion(nil);
        }];
    }
}


/*
- (void)updateValuetoTable:(NSString *)tablename withArray:(NSArray *)array{
    int i = 0;
    for (NSDictionary *dic in array) {
        NSMutableString *keyString = [NSMutableString string];
        
        int idx = 0;
        for (NSString *key in dic.allKeys) {
            NSString *val = [dic objectForKey:key];
            
            if ([val isKindOfClass:[NSString class]] && val.length==0) {
                val = @"''";
            }else if([val isKindOfClass:[NSString class]]){
                val = [NSString stringWithFormat:@"'%@'",val];
            }
            
            [keyString appendFormat:@"%@ = %@",key,val];
            if (idx!=dic.allKeys.count-1) {
                [keyString appendString:@","];
            }

            idx++;
        }
        
        
        NSString *sql = [NSString stringWithFormat:@"update %@ set %@",tablename,keyString];
        BOOL r = [self excuteSQL:sql];
        if (r==NO) {//如果插入失败，尝试更新操作
            NSLog(@"error,%d",i);
        }
        i++;
    }
}
 */

- (BOOL)insertValueToTable:(NSString *)tablename withArray:(NSArray *)array byKey:(NSArray *)keys{
    return [self insertValueToTable:tablename withArray:array byKey:keys enableTransaction:YES];
}

- (BOOL)insertValueToTable:(NSString *)tablename withArray:(NSArray *)array byKey:(NSArray *)keys enableTransaction:(BOOL)enable{
    if (array.count==0) {
        return YES;
    }
    
    if (enable) {
        [db_ beginTransaction];
    }
    
    
    int i = 0;
    for (NSDictionary *dic in array) {
        NSMutableString *keyString = [NSMutableString string];
        NSMutableString *valString = [NSMutableString string];
        
        int idx = 0;
        for (NSString *key in dic.allKeys) {
            id val = [dic objectForKey:key];
            
            if ([val isKindOfClass:[NSString class]] && ((NSString *)val).length==0) {
                val = @"''";
            }else if([val isKindOfClass:[NSString class]]){
                val = [NSString stringWithFormat:@"'%@'",val];
            }
            
            [keyString appendFormat:@"%@",key];
            if (idx!=dic.allKeys.count-1) {
                [keyString appendString:@","];
            }
            
            
            [valString appendFormat:@"%@",val];
            if (idx!=dic.allKeys.count-1) {
                [valString appendString:@","];
            }
            
            idx++;
        }
        
        NSMutableString *condition = [NSMutableString stringWithString:@""];;
        if (keys!=nil) {
            condition = [NSMutableString stringWithString:@"where "];
            int i = 0;
            for ( NSString *cKey in keys ) {
                NSString *cVal = [dic objectForKey:cKey];
                if ([cVal isKindOfClass:[NSString class]] && cVal.length==0) {
                    cVal = @"''";
                }else if([cVal isKindOfClass:[NSString class]]){
                    cVal = [NSString stringWithFormat:@"'%@'",cVal];
                }
                
                [condition appendFormat:@"%@=%@",cKey,cVal];
                
                if (i!=keys.count-1) {
                    [condition appendFormat:@" and "];
                }
                i++;
            }
        }
        
        if (keyString.length == 0) {
            continue;
        }
        
        BOOL r = NO;
        NSString *sql=@"" ;
        if (keys) {
            sql = [NSString stringWithFormat:@"delete from %@ %@",tablename,condition];
            r= [self excuteSQL:sql];
        }else{
            
        }

        sql = [NSString stringWithFormat:@"insert into %@(%@) values(%@)",tablename,keyString,valString];
        r = [self excuteSQL:sql];
        if (r==NO) {//如果插入失败，尝试更新操作
            NSLog(@"error,%d,sql=%@",i,sql);
        }
        i++;
    }
    
    if (enable) {
        [db_ commit];
    }
    
    
    return YES;
}
//
- (void)refreshSuitTable:(DMCompletion)completion{

    [self deleteTable:@"g_billd_Assembling"];
    [self deleteTable:@"g_billm_Assembling"];
    [self updateSuitPm:^(NSArray *array){
        
        completion(nil);
    }];
}

- (void)refreshReferenceTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshReferenceTable:^(NSArray *array){
        if (array.count>0) {
            [self deleteTable:@"ReferencePara"];
            [self insertValueToTable:@"ReferencePara" withArray:array byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)refreshSizeTable:(DMCompletion)completion{
    
    
    [[WebServiceManager sharedManager] refreshSizeTable:^(NSArray *array){
        if (array.count>0) {
            [self deleteTable:@"r_size"];
            [self insertValueToTable:@"r_size" withArray:array byKey:nil];
        }

        completion(nil);
    }];
}

- (void)refreshTipsTable{
    
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSDate *date = [formatter dateFromString:@"1900-01-01 00:00:00"];
    NSString *time = [formatter stringFromDate:date];
    [[WebServiceManager sharedManager] gettip:userObject_.userCode time:time completion:^(NSArray *array){
        if (array.count>0) {
            [self deleteTable:@"tips"];
            [self insertValueToTable:@"tips" withArray:array byKey:nil];
        }
        
    }];
}

-(void)refreshSpdmOrderTable:(DMCompletion)completion
{

    [[WebServiceManager sharedManager] getSpdmOrder:^(NSArray *array){
        if (array.count>0) {
            [self deleteTable:@"spdmorder"];
            [self insertValueToTable:@"spdmorder" withArray:array byKey:nil];
        }
        
        completion(nil);
    }];
}

-(void)refreshg_SizeTable:(DMCompletion)completion
{
    
    
    [[WebServiceManager sharedManager] refreshg_SizeTable:0 completion:^(NSArray *array){
        if (array.count>0) {
            [self deleteTable:@"g_size"];
            [self insertValueToTable:@"g_size" withArray:array byKey:nil];
        }
        
        completion(nil);
    }];
}

- (void)deleteOrderItem:(OrderObject *)order withSizeNo:(NSString *)size withTableName:(NSString *)tablename Shopid:(NSString*)shopid{
    NSString *sql;
    if (size) {
        sql = [NSString stringWithFormat:@"delete from %@ where code = '%@' and colorid = '%@' and xsize = '%@' and shopid = '%@'",
                         tablename,order.pCode,order.pColorCode,size,shopid];
    }
    else
    {
        sql = [NSString stringWithFormat:@"delete from %@ where code = '%@' and colorid = '%@' and shopid = '%@'",
               tablename,order.pCode,order.pColorCode,shopid];
    }
    
    [self excuteSQL:sql];
}

- (void)addOrder:(OrderObject *)order withSizeNo:(NSString *)size byAmout:(int)amount Shopid:(NSString*)shopid{
    
    [self deleteOrderItem:order withSizeNo:size withTableName:@"g_meeting" Shopid:shopid];
    //[self deleteOrderItem:order withSizeNo:size withTableName:@"g_meeting2" Shopid:shopid];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *formattedString = [dateFormatter stringFromDate:[NSDate date]];
//    ProductObject* product = [self getProductObjectByName:order.pCode andColor:order.pColorCode];
    [dict setObject:shopid forKey:@"shopid"];
    [dict setObject:formattedString forKey:@"iotime"];
    [dict setObject:order.pCode forKey:@"code"];
    [dict setObject:order.pColorCode forKey:@"colorid"];
    [dict setObject:size forKey:@"xsize"];
    [dict setObject:[NSNumber numberWithInt:amount] forKey:@"amount"];
//    [dict setObject:[NSNumber numberWithInt:product.pSale] forKey:@"price"];
//    [dict setObject:[NSNumber numberWithFloat:product.pRatio] forKey:@"rebate"];
//    [dict setObject:[NSNumber numberWithInt:(amount*product.pSale)] forKey:@"sale"];
//    [dict setObject:[NSNumber numberWithInt:product.pSale] forKey:@"orgprice"];
    [dict setObject:@""  forKey:@"c_zuangtm"];
    [dict setObject:@""  forKey:@"n_sample"];
    [dict setObject:[[self getUserObject] userCode] forKey:@"usercode"];
    [dict setObject:@"" forKey:@"MaxSynID"];
    
    NSArray* arr = [[NSArray alloc]initWithObjects:dict,nil];
    
    NSArray *keys = [NSArray arrayWithObjects:@"code",@"colorid",@"xsize",@"shopid",
                     nil];
    [self insertValueToTable:@"g_meeting" withArray:arr byKey:keys enableTransaction:NO];
    
}
- (int)getOrderAmount:(ProductObject *)product Shopid:(NSString*)shopid{
    NSString* sql = @"";
    if (shopid) {
       // sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where shopid = '%@' and usercode = '%@' and (code ='%@' or  code ='%@K' or code ='%@JK')  and colorid = '%@' and amount<>0 ",shopid,[[DataManager sharedManager] getUserObject].userCode,product.pCode,product.pCode,product.pCode,product.pColorCode ];
        sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where shopid = '%@' and (code ='%@' or  code ='%@K' or code ='%@JK')  and amount<>0 ",shopid,product.pCode,product.pCode,product.pCode ];
    }
    else{
       // sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where usercode = '%@' and (code ='%@' or  code ='%@K' or code ='%@JK')  and colorid = '%@' and amount<>0 ",[[DataManager sharedManager] getUserObject].userCode,product.pCode,product.pCode,product.pCode,product.pColorCode ];
        sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where (code ='%@' or  code ='%@K' or code ='%@JK') and amount<>0 ",product.pCode,product.pCode,product.pCode ];
    }
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [rs intForColumn:@"sumamount"];
    }
    return 0;
}

- (int)getOrderAmountWithCode:(ProductObject *)product Shopid:(NSString*)shopid{
    NSString* sql = @"";
    if (shopid) {
        sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where shopid = '%@' and (code ='%@' or  code ='%@K' or code ='%@JK')  and amount<>0 ",shopid,product.pCode,product.pCode,product.pCode ];
    }
    else{
        sql = [NSString stringWithFormat:@"select sum(amount) sumamount from g_meeting where (code ='%@' or  code ='%@K' or code ='%@JK')  and amount<>0 ",product.pCode,product.pCode,product.pCode ];
    }
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [rs intForColumn:@"sumamount"];
    }
    return 0;
}

- (NSMutableDictionary*)getOrderAmount:(NSString*)shopid{
    NSMutableDictionary* result = [[NSMutableDictionary alloc]init];
    NSString* sql = [NSString stringWithFormat:@"select sum(amount) cnt,sum(sale) amount from g_meeting where  shopid = '%@' ",shopid];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        [result setObject:[NSNumber numberWithInt:[rs intForColumn:@"cnt"]] forKey:@"count"];
        [result setObject:[NSNumber numberWithInt:[rs doubleForColumn:@"amount"]] forKey:@"amount"];
        return result;
    }
    return result;
}

- (int)getOrderAmountBySizeNo:(ProductObject *)product Shopid:(NSString*)shopid size:(NSString *)sizeNo{
    NSString* sql = [NSString stringWithFormat:@"select amount from g_meeting where shopid = '%@' and code ='%@' and colorid = '%@' and xsize ='%@' and amount<>0  ",shopid,product.pCode,product.pColorCode,sizeNo ];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return [rs intForColumn:@"amount"];
    }
    return 0;
}


-(OrderObject*)getOrderByProduct:(ProductObject*)product Shopid:(NSString*)shopid{
    OrderObject* neworder = [[OrderObject alloc]initWithProduct:product];
    NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
//    NSString* sql = [NSString stringWithFormat:@"select * from g_meeting where shopid = '%@' and usercode = '%@' and code ='%@' and colorid = '%@' and amount<>0",shopid,[[DataManager sharedManager] getUserObject].userCode,product.pCode,product.pColorCode];
    NSString* sql = [NSString stringWithFormat:@"select * from g_meeting where shopid = '%@' and code ='%@' and colorid = '%@' ",shopid,product.pCode,product.pColorCode];

    FMResultSet *rs = [db_ executeQuery:sql];
    
    while ([rs next]) {
        
        [dict setObject:[NSNumber numberWithInt: [rs intForColumn:@"amount"]] forKey:[NSString stringWithFormat:@"%@_%@",[rs stringForColumn:@"xsize"],shopid]];
        
    }
    neworder.quantity = dict;
    return neworder;
}

- (NSMutableArray *)getOrderedWithFilter:(NSString *)shopid Submit:(int)flag filter:(NSArray *)filters{
    
    NSString* sql =@"";
    NSMutableArray* result = [[NSMutableArray alloc] init];
    // NSMutableArray *orderarray = [[NSMutableArray alloc]init];
    
    
    NSString* condition = @" ";
    for (int i = 0; i<filters.count; i++) {
        
        KeyObject* key = [filters objectAtIndex:i];
        
        if (key.keyIndex!=0) {
            condition = [condition stringByAppendingFormat:@" and %@ = '%@'",key.columnname,key.keyName ];
        }
        
    }
    
    if (shopid) {
        
        sql = [NSString stringWithFormat:@"select g.shopid,g.code,max(g.colorid) as colorid,max(v.c_url) as c_url,max(v.sale) as sale,sum(g.amount) amount,v.codename,v.n_status from g_meeting g left join v_g_spdm v on g.code=v.code and g.colorid=v.colorid group by g.shopid,g.code,v.codename,v.n_status having g.shopid = '%@'",shopid];
        
        sql = [sql stringByAppendingString:condition];

    }
    else{
        sql = [NSString stringWithFormat:@"select * from g_meeting"];
    }
    
    if (flag==0) {
        //未同步订单
        sql = [sql stringByAppendingString:@" and g.MaxSynID = ''"];
        sql = [sql stringByAppendingString:@" and n_status=0"];
    }
    else if(flag==3)
    {
        // sql = [sql stringByAppendingString:@" and MaxSynID <> ''"];
        sql = [sql stringByAppendingString:@"and sum(g.amount)>0"];
    }
    else if (flag==4)
    {
    }
    else if(flag==1){
        
        sql = [sql stringByAppendingString:@" and n_status=0"];
        sql = [sql stringByAppendingString:@" and g.MaxSynID <> ''"];
        sql = [sql stringByAppendingString:@" and sum(g.amount)>0"];
    }
    else {
        // sql = [sql stringByAppendingString:@" and amount>0 and MaxSynID <> ''"];
        sql = [sql stringByAppendingString:@" and sum(g.amount)>0"];
        sql = [sql stringByAppendingString:@" and n_status=1"];
    }
    
    sql = [sql stringByAppendingFormat:@" order by %@ ",@"v.c_xilbh,g.code,g.colorid"];
    
    // sql = [sql stringByAppendingString:@" order by scripno"];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        [result addObject:[rs resultDictionary]];
    }
    return result;
}


- (NSMutableArray *)getOrdered:(NSString*)shopid Submit:(int)flag{
    return [self getOrderedWithFilter:shopid Submit:flag filter:nil];
}




- (NSMutableArray *)getOrderInfo:(NSString*)shopid Submit:(int)flag{
    NSString* sql =@"";
    NSMutableArray* result = [[NSMutableArray alloc] init];
    
    if (shopid) {
        sql = [NSString stringWithFormat:@"select distinct code,colorid from g_meeting where shopid = '%@'",shopid];
    }
    else{
        sql = [NSString stringWithFormat:@"select distinct code,colorid from g_meeting where"];
    }
    
    if (flag==0) {
        //未同步订单
        sql = [sql stringByAppendingString:@" and MaxSynID = ''"];
    }
    else if (flag ==1){
        sql = [sql stringByAppendingString:@" and MaxSynID <> ''"];
    }
    //如果flag为4的会默认返回所有订单的，但在这里没用else来体现；
    
    sql = [sql stringByAppendingString:@" order by scripno"]; 
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        
        OrderObject* order = [self getOrderInfoByItem:shopid Code:[rs stringForColumn:@"code"] Colorid:[rs stringForColumn:@"colorid"] Submit:flag];
        
        [result addObject:order];
        
    }
    
    return result;
}


- (OrderObject *)getOrderInfoByItem:(NSString*)shopid Code:(NSString*)code Colorid:(NSString*)colorid Submit:(int)flag{
    
    NSString* sql =@"";
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
    
    if (shopid) {
        sql = [NSString stringWithFormat:@"select * from g_meeting where shopid = '%@' and code = '%@' and colorid = '%@' ",shopid,code,colorid];
    }
    else{
        sql = [NSString stringWithFormat:@"select * from g_meeting where code = '%@' and colorid = '%@' ",code,colorid];
    }
    
    if (flag==0) {
        //未同步订单
        sql = [sql stringByAppendingString:@" and MaxSynID = ''"];
    }
    else{
        sql = [sql stringByAppendingString:@" and MaxSynID <> ''"];
    }
   sql = [sql stringByAppendingString:@" order by scripno"]; 
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        if (shopid) {
            [dict setObject:[NSNumber numberWithInt:[rs intForColumn:@"amount"]] forKey:[NSString stringWithFormat:@"%@_%@",[rs stringForColumn:@"xsize"],shopid]];
        }else{
            [dict setObject:[NSNumber numberWithInt:[rs intForColumn:@"amount"]] forKey:[NSString stringWithFormat:@"%@_%@",[rs stringForColumn:@"xsize"],[rs stringForColumn:@"shopid"]]];
        }
    
        
    }
    
    OrderObject* order = [[OrderObject alloc]init];

    order.pCode = code;
    order.pColorCode = colorid ;

    order.quantity = dict;

    return  order;

}


-(NSMutableArray*)getOrderStat:(KeyObject*)key Shopid:(NSString*)shopid{
    NSString* sql =@"";
    NSArray* keyarr = [self getChildrenKeyObjects:key.keyID];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    KeyObject* childkey = (KeyObject*)[keyarr objectAtIndex:0];
    
    NSString* colunmname = childkey.columnname;
    
    if (shopid) {
        sql = [NSString stringWithFormat:@"select a2.%@ name, sum(a1.amount) totalamt,sum(a1.sale) totalprice from g_meeting a1 join v_g_spdm a2 on a1.code = a2.code and a1.colorid = a2.colorid where a1.shopid = '%@'",colunmname,shopid];
    }
    else{
        sql = [NSString stringWithFormat:@"select a2.%@ name, sum(a1.amount) totalamt,sum(a1.sale) totalprice from g_meeting a1 join v_g_spdm a2 on a1.code = a2.code and a1.colorid = a2.colorid ",colunmname];
    }
    
    if (key.keyName) {
        sql = [sql stringByAppendingFormat:@" and a2.%@='%@' ",key.columnname,key.keyName];
    }

    sql = [sql stringByAppendingString:@" group by name having totalamt <>0 "];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
        
        [dict setObject:[rs stringForColumn:@"name"] forKey:@"name"];
        [dict setObject:[NSNumber numberWithInt:[rs intForColumn:@"totalamt"]] forKey:@"count"];
        [dict setObject:[NSNumber numberWithInt:[rs doubleForColumn:@"totalprice"]] forKey:@"amount"];
        
        [result addObject:dict];
    }
    
    
    return result;
}

-(NSArray*)getStatType{
    NSString* sql =@"select * from ReportType where b_visible='1' order by nIndex";
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
        
        [dict setObject:[rs stringForColumn:@"name"] forKey:@"name"];
        [dict setObject:[NSNumber numberWithInt:[rs intForColumn:@"seq"]] forKey:@"seq"];
        
        [result addObject:dict];
    }
    
    return result;
}

-(NSArray*)getOrderReportColumnCName:(int)reportId{
    switch (reportId) {
        case 1:
        {
            //按展厅查询
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            //按品类查询
            return [NSArray arrayWithObjects:a, nil];
        }
            
        case 2:
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            //按品类查询
            return [NSArray arrayWithObjects:a, nil];
        }
            
            break;
        case 3:
            //按小类查询
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            
            break;
        case 4:
        {
            NSArray *a =[[NSArray alloc]initWithObjects:@"款名",@"款号",@"总数量",@"总金额",@"款数",@"SKU数",@"数量占比",@"金额占比", nil];
            //按款查询
            return [NSArray arrayWithObjects:a, nil];
        }

            break;
        case 5:
            //按波段/按季节
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            
            break;
        case 6:
            //按风格
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            break;
        case 7:
            //按颜色
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"颜色编号",@"颜色名称",@"总数量",@"总金额",@"款数",@"SKU数",@"数量占比",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            break;
        case 8:
        {
            NSMutableArray *res = [NSMutableArray array];
            NSArray *groups = [self getSizeGroup];
            int idx = 0;
            
            NSString *sql = nil;
            
            int maxcol = 0;
            sql = @"select max(cast(sizeno as int))+1 as sizeno from r_size";
            FMResultSet *rs = [db_ executeQuery:sql];
            while ([rs next]) {
                maxcol = [rs intForColumn:@"sizeno"];
            }
            
            
            for (NSDictionary *d in groups) {
                NSMutableArray *a =  nil;
                if (idx==0) {
                    a = [[NSMutableArray alloc]initWithObjects:@"款号",@"花型",@"品名规格",@"总数量",@"总金额",nil];
                }else{
                    a = [[NSMutableArray alloc]initWithObjects:@"",@"",@"",@"",@"",nil];
                }
                
                
                NSString *groupno = [d objectForKey:@"groupno"];
                NSArray *sizes = [self getSizeListBySizeGroup:[groupno intValue] SizeType:nil];
                NSMutableArray *b = [NSMutableArray array];
                
                for (int i = 0; i < maxcol; i++) {
                    if (i < sizes.count) {
                        SizeObject *obj = [sizes objectAtIndex:i];
                        [b addObject:obj.sSizeName];
                    }else{
                        [b addObject:@""];
                    }
                    
                }
                [a addObjectsFromArray:b];
                [res addObject:a];
                
                
                idx++;
            }
            
            return res;
        }
            break;
            
        case 9:
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            break;
        case 10:
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            break;
        case 11:
        {
            NSArray *a = [[NSArray alloc]initWithObjects:@"名称",@"订货款数",@"款数占比",@"SKU数",@"SKU占比",@"数量",@"数量占比",@"金额",@"金额占比", nil];
            return [NSArray arrayWithObjects:a, nil];
        }
            break;
            /*
        case 7:
            //按全国排行
            return [[NSArray alloc]initWithObjects:@"小类名称",@"款式名称",@"款式编号",@"排名",@"图片", nil];
            break;
        case 9:
            //按省排行
            return [[NSArray alloc]initWithObjects:@"小类名称",@"款式名称",@"款式编号",@"排名",@"图片", nil];
            break;
        case 10:
            //按全国排行过滤小类
            return [[NSArray alloc]initWithObjects:@"小类名称",@"款式名称",@"款式编号",@"排名", nil];
            break;
        case 11:
            //按全国排行
            return [[NSArray alloc]initWithObjects:@"小类名称",@"款式名称",@"款式编号",@"排名", nil];
            break;
*/
            
        default:
            break;
    }
    return nil;
}

- (int)getColumnWidth:(int)reportId column:(int)idx{
    switch (reportId) {
        case 8:
        {
            if (idx<1) {
                return 0;
            }else if(idx==2){
                return 200;
            }else if(idx<5){
                return 100;
            }else{
                return 60;
            }
        }
            break;
        case 4:
            return 110;
            break;
        default:
            if (idx==1||idx==3||idx==5) {
                return 80;
            }
            return 110;
            break;
    }
}



-(NSArray*)getOrderReport:(int)reportId Filter:(KeyObject*)key Shopid:(NSString*)shopid{
    
    int qty = 0;
    double sumAmount = 0.0000;
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"and g.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"and g.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    NSString *sql = [NSString stringWithFormat:@"select ifnull(sum(g.amount),0) qty ,ifnull(sum(g.amount*v.sale),0) sumAmount,count(distinct g.code || '-' || g.colorid) as skuamount,count(distinct g.code) codeamount from g_meeting g left join v_g_spdm v on g.code=v.code and g.colorid=v.colorid where g.amount>0 and (v.n_status =0) %@ ",shopstring];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    NSDictionary *resDic = nil;
    while ([rs next]) {
        //sumAmount = [rs doubleForColumn:@"sumAmount"];
        resDic = [rs resultDictionary];
    }
    
    switch (reportId) {
        case 1:
            return [self Queryexhibition:shopid result:resDic];
            break;
        case 2:
            return [self QueryType:shopid result:resDic];
            break;
        case 3:
            return [self QueryStyle:shopid result:resDic];
            break;
        case 4:
            return [self QueryCode:shopid result:resDic];
            break;
        case 5:
            return [self QuerySeason:shopid result:resDic];
            break;
        case 6:
            return [self QueryXilie:shopid result:resDic];
            break;
        case 7:
            return [self QueryColor:shopid result:resDic];
            break;
        case 8:
            return [self QueryDetail:shopid result:resDic];
            break;
        case 9:
            return [self QueryXingBie:shopid result:resDic];
            break;
        case 10:
            return [self QueryBoDuan:shopid result:resDic];
            break;
        case 11:
            return [self QuerySaleSegment:shopid result:resDic];
            break;
        default:
            break;
    }
    return nil;
}

//明细报表
- (NSArray *)QueryDetail:(NSString *)shopid result:(NSDictionary *)dic{
    NSString* shopstring = @" ";
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
//    int sku = [[dic objectForKey:@"skuamount"] intValue];
//    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"a.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"a.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    NSString *sql = nil;
    
    int maxcol = 0;
    sql = @"select max(cast(sizeno as int))+1 as sizeno from r_size";
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        maxcol = [rs intForColumn:@"sizeno"];
    }
    NSMutableString *mutalSQL = [NSMutableString string];
    for (int i = 0; i < maxcol; i++) {
        NSString *s = [NSString stringWithFormat:@" ,sum(case a.xsize when %d then a.amount else null end) as size%d",i,i];
        
        [mutalSQL appendString:s];
    }
    sql=[NSString stringWithFormat:@"select a.code,b.codename,b.colorname, sum(a.amount) as totalcount,sum(a.amount*b.sale) as totalmoney  %@  from g_meeting a left join v_g_spdm b on a.code=b.code and a.colorid=b.colorid where %@ and a.amount>0 and b.n_status=0 group by a.code,b.codename,b.colorname order by a.code",mutalSQL,shopstring];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    rs = [db_ executeQuery:sql];
    int maxCol = 0;
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        maxCol = [rs columnCount];
        for (int i = 0; i < [rs columnCount]; i++) {
            if ([rs stringForColumnIndex:i]) {
                [detail addObject:[rs stringForColumnIndex:i]];
            }else{
                [detail addObject:@""];
            }
            
        }
        
        [result addObject:detail];
    }
    
    NSString *t1 = [NSString stringWithFormat:@"%d",qty];
    NSString *t2 = [NSString stringWithFormat:@"%.2f",amt];
    
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"总计",@"",@"",t1,t2,nil];
    [result addObject:arr];
    for (int i = 0;i<maxCol-5;i++) {
        [arr addObject:@""];
    }
    
    
    return result;
}


//按展厅查询
//-(NSArray*)Queryexhibition:(NSString*)shopid Qty:(int)qty Amt:(double)amt{
-(NSArray*)Queryexhibition:(NSString*)shopid  result:(NSDictionary *)dic{

    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select c_zhanting as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_zhanting) as a",qty,amt,codeAmount,sku,shopstring];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        //        [detail addObject:[rs stringForColumn:@"c_xilbh"]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    
    return result;
    
//    NSString* shopstring = @" ";
//    
//    
//    if (shopid && shopid.length>0) {
//        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
//    }else{
//        UserObject *obj = [[DataManager sharedManager] getUserObject];
//        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
//    }
//    
//    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from (select  c_zhanting as mingc, sum(amount) as totalcount,cast(sum(amount*sale) as numeric(18,2))as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct  code || '-' || colorid) as skucount from (select  g1.code,g1.colorid,g1.amount,g2.c_zhanting,g2.sale,g2.price  from g_meeting g1 left join v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@ and g2.n_status=0 and g1.amount>0) as gg  group  by c_zhanting) as a",qty,amt,shopstring ];
//    NSMutableArray* result = [[NSMutableArray alloc] init];
//    FMResultSet *rs = [db_ executeQuery:sql];
//    while ([rs next]) {
//        NSMutableArray* detail = [[NSMutableArray alloc]init];
//        
//        [detail addObject:[rs stringForColumn:@"mingc"]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
//
//        [result addObject:detail];
//    }
//    
//    sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from (select '总计' as mingc, sum(amount) as totalcount,cast(sum(amount*sale) as numeric(18,2))as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct  code || '-' || colorid) as skucount from (select  g1.code,g1.colorid,g1.amount,g2.c_zhanting,g2.sale,g2.price  from g_meeting g1 left join v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg) as a ",qty,amt,shopstring ];
//    
//    rs = [db_ executeQuery:sql];
//    while ([rs next]) {
//        NSMutableArray* detail = [[NSMutableArray alloc]init];
//        
//        [detail addObject:[rs stringForColumn:@"mingc"]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
//        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
//        
//        [result addObject:detail];
//    }
//    
//    
//    return result;
    
}

//按品类查询
-(NSArray*)QueryType:(NSString*)shopid  result:(NSDictionary *)dic{
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select c_xilbh, c_xilmc as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_xilbh ,c_xilmc ,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_xilbh, c_xilmc) as a",qty,amt,codeAmount,sku,shopstring];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
//        [detail addObject:[rs stringForColumn:@"c_xilbh"]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
}
    
    
    return result;
    
}

//按小类查询
-(NSArray*)QueryStyle:(NSString*)shopid result:(NSDictionary *)dic{
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
//    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney    from(select c_kuansbh,c_kuansmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from(select g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price  from g_meeting g1 left join   v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status<>2 and g1.amount>0) as gg  group  by c_kuansbh, c_kuansmc) as a",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  ifnull(c_kuansmc,'') as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_kuansmc) as a",qty,amt,codeAmount,sku,shopstring];

    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];

    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];

    }

    
    return result;
    
}

//按款查询
-(NSArray*)QueryCode:(NSString*)shopid result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
//    int sku = [[dic objectForKey:@"skuamount"] intValue];
//    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney    from (select codename,code as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g1.code,g2.codename,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where  g2.n_status=0 and %@ and g1.amount>0) as gg  group  by code, codename ) as a",qty,amt,shopstring];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"codename"]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    
    sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney    from (select '总计' codename,'' as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g1.code,g2.codename,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status=0 and %@ and g1.amount>0) as gg ) as a ",qty,amt,shopstring];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"codename"]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    return result;
    
}


//按波段/按季节
-(NSArray*)QuerySeason:(NSString*)shopid result:(NSDictionary *)dic{
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    //NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) )as fmoney    from (select c_jijbh, c_jijmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' ||colorid) as skucount from (select g2.c_jijbh,c_jijmc,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status<>2 and %@ and g1.amount>0) as gg  group  by c_jijbh, c_jijmc  ) as a",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  c_jijmc as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_jijmc,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_jijmc) as a",qty,amt,codeAmount,sku,shopstring];
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }

    
    
    return result;
    
}

//按性别
#pragma mark 性别报表
-(NSArray*)QueryXingBie:(NSString*)shopid  result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    //NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) )as fmoney    from (select c_xiaoxlbh,c_xiaoxlmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g2.c_fenggbh c_xiaoxlbh,c_fenggmc c_xiaoxlmc,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status<>2 and %@  and g1.amount>0) as gg  group  by c_xiaoxlbh, c_xiaoxlmc ) as a ",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  c_xingb as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_xingb,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_xingb) as a",qty,amt,codeAmount,sku,shopstring];
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    return result;
    
}

//按波段(item3)
#pragma mark 波段(item3)
-(NSArray*)QueryBoDuan:(NSString*)shopid  result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    //NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) )as fmoney    from (select c_xiaoxlbh,c_xiaoxlmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g2.c_fenggbh c_xiaoxlbh,c_fenggmc c_xiaoxlmc,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status<>2 and %@  and g1.amount>0) as gg  group  by c_xiaoxlbh, c_xiaoxlmc ) as a ",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  item3 as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,item3,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by item3) as a",qty,amt,codeAmount,sku,shopstring];
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    return result;
    
}

//按价格段
#pragma mark 价格段
-(NSArray*)QuerySaleSegment:(NSString*)shopid  result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    //NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) )as fmoney    from (select c_xiaoxlbh,c_xiaoxlmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g2.c_fenggbh c_xiaoxlbh,c_fenggmc c_xiaoxlmc,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status<>2 and %@  and g1.amount>0) as gg  group  by c_xiaoxlbh, c_xiaoxlmc ) as a ",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  nid,c_zidm as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,pr.c_zidm,pr.nid,n_jiny,g2.sale ,g2.price  from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code left join r_dictvalue pr on (g2.sale between pr.n_minvalue and pr.n_maxvalue ) where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_zidm,nid) as a order by nid",qty,amt,codeAmount,sku,shopstring];
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    return result;
    
}


//按风格
-(NSArray*)QueryXilie:(NSString*)shopid  result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
    int sku = [[dic objectForKey:@"skuamount"] intValue];
    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    //NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) )as fmoney    from (select c_xiaoxlbh,c_xiaoxlmc as mingc, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select g2.c_fenggbh c_xiaoxlbh,c_fenggmc c_xiaoxlmc,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1  left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status<>2 and %@  and g1.amount>0) as gg  group  by c_xiaoxlbh, c_xiaoxlmc ) as a ",qty,amt,shopstring];
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) ) as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney  from(select  c_fenggmc as mingc,sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount, count(distinct code || '-' || colorid) as skucount ,cast(cast(count(distinct code) as float) / %d  * 100 as numeric(18,2) ) as fcodecount,cast(cast(count(distinct code || '-' || colorid) as float) / %d  * 100 as numeric(18,2) ) as fskuamount from (select g1.code,g1.colorid,g1.amount,c_fenggmc,c_zhanting,n_jiny,g2.sale,g2.price   from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where %@  and g2.n_status=0 and g1.amount>0) as gg  group  by c_fenggmc) as a",qty,amt,codeAmount,sku,shopstring];
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    sql = [NSString stringWithFormat:@"select  '总计' as mingc,%d as totalcount, %f as totalmoney,%d as codecount,%d as skucount, 100 as fqry, 100 as fmoney ,100 as fskuamount,100 as fcodecount ",qty,amt,codeAmount,sku];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fcodecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fskuamount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
        
    }
    
    return result;
    
}

//按颜色
-(NSArray*)QueryColor:(NSString*)shopid  result:(NSDictionary *)dic{
    
    int qty = [[dic objectForKey:@"qty"] intValue];
    float amt = [[dic objectForKey:@"sumAmount"] floatValue];
//    int sku = [[dic objectForKey:@"skuamount"] intValue];
//    int codeAmount = [[dic objectForKey:@"codeamount"] intValue];
    
    NSString* shopstring = @" ";
    
    
    if (shopid && shopid.length>0) {
        shopstring = [NSString stringWithFormat:@"g1.shopid='%@'",shopid];
    }else{
        UserObject *obj = [[DataManager sharedManager] getUserObject];
        shopstring = [NSString stringWithFormat:@"g1.shopid in (select shopid from shops where usercode='%@')",obj.userCode];
    }
    
    NSString* sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) )as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney    from (select colorname as mingc,colorid, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select colorname,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status=0 and %@ and g1.amount>0) as gg  group  by colorid,colorname) as a order by colorid",qty,amt,shopstring];
    NSMutableArray* result = [[NSMutableArray alloc] init];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[NSString stringWithFormat:@"%03d",[rs intForColumn:@"colorid"]]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    sql = [NSString stringWithFormat:@"select a.* , cast(cast(a.totalcount as float) / %d  * 100 as numeric(18,2) )as fqry,cast(cast(a.totalmoney as numeric(18,4)) / %f * 100 as numeric(18,2) ) as fmoney    from (select '' as mingc,'总计' as colorid, sum(amount) as totalcount, sum(amount*sale) as totalmoney,sum(amount*cast(Round(price, 0) as numeric(18,0))) as RebateMoney,count(distinct code) as codecount,count(distinct code || '-' || colorid) as skucount from (select colorname,g1.code,g1.colorid,g1.amount ,c_kuansbh ,c_kuansmc ,c_zhanting,n_jiny,g2.sale,g2.price from g_meeting g1 left join  v_g_spdm  g2 on g1.code=g2.code and g1.colorid=g2.colorid where g2.n_status=0 and %@ and g1.amount>0) as gg ) as a  order by colorid",qty,amt,shopstring];
    
    rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSMutableArray* detail = [[NSMutableArray alloc]init];
        
        [detail addObject:[rs stringForColumn:@"colorid"]];
        [detail addObject:[rs stringForColumn:@"mingc"]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"totalcount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f",[rs doubleForColumn:@"totalmoney"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"codecount"]]];
        [detail addObject:[NSString stringWithFormat:@"%d",[rs intForColumn:@"skucount"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fqry"]]];
        [detail addObject:[NSString stringWithFormat:@"%.2f%%",[rs doubleForColumn:@"fmoney"]]];
        
        [result addObject:detail];
    }
    
    return result;
}


- (void)markOrderAsUploaded:(OrderObject *)obj time:(NSString *)upload shop:(ShopObject *)shop{
//      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//      dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//      NSString *dateString = [dateFormatter stringFromDate:upload];

    
    NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '%@' where code = '%@' and colorid = '%@' and shopid = '%@'",upload,obj.pCode,obj.pColorCode,shop.shopID];
    [self excuteSQL:sql];
}


- (void)clearOrderUptime{

    ShopObject *shop = [self getCurrentShop];
    NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '',d_upid='' where shopid = '%@' ",shop.shopID];
    [self excuteSQL:sql];
}


-(NSArray*)transReport:(NSDictionary*)dict{
    
    NSMutableArray* result = [[NSMutableArray alloc]init];
    
    if ([dict objectForKey:@"c_kuansmc"]) {
        [result addObject:[dict objectForKey:@"c_kuansmc"]];
    }
    if ([dict objectForKey:@"codename"]) {
        [result addObject:[dict objectForKey:@"codename"]];
    }
    if ([dict objectForKey:@"mingc"]) {
        if([[dict objectForKey:@"mingc"] isKindOfClass:[NSString class]]){
            [result addObject:[dict objectForKey:@"mingc"]];
        }
        else{
            [result addObject:[NSString stringWithFormat:@"%d",[[dict objectForKey:@"mingc"]intValue]]];
        }
    }
    
    if ([dict objectForKey:@"num"]) {
        [result addObject:[NSString stringWithFormat:@"%d",[[dict objectForKey:@"num"]intValue]]];
    }
    
    if ([dict objectForKey:@"totalcount"]) {
        [result addObject:[NSString stringWithFormat:@"%d",[[dict objectForKey:@"totalcount"]intValue]]];
    }
    if ([dict objectForKey:@"totalmoney"]) {
        [result addObject:[NSString stringWithFormat:@"%.2f",[[dict objectForKey:@"totalmoney"]floatValue]]];
    }
    if ([dict objectForKey:@"codecount"]) {
        [result addObject:[NSString stringWithFormat:@"%d",[[dict objectForKey:@"codecount"]intValue]]];
    }
    if ([dict objectForKey:@"skucount"]) {
        [result addObject:[NSString stringWithFormat:@"%d",[[dict objectForKey:@"skucount"]intValue]]];
    }
    if ([dict objectForKey:@"fqry"]) {
        if([[dict objectForKey:@"fqry"] isKindOfClass:[NSString class]]){
            [result addObject:[dict objectForKey:@"fqry"]];
        }
        else{
            [result addObject:[NSString stringWithFormat:@"%.2f%%",[[dict objectForKey:@"fqry"]floatValue]]];
        }
    }

    if ([dict objectForKey:@"fmoney"]) {
        if([[dict objectForKey:@"fmoney"] isKindOfClass:[NSString class]]){
            [result addObject:[dict objectForKey:@"fmoney"]];
        }
        else{
            [result addObject:[NSString stringWithFormat:@"%.2f%%",[[dict objectForKey:@"fmoney"]floatValue]]];
        }
    }
    
    return result;
}

- (NSString *)getUserDesc{
    if (shops_.count>0) {
        //ShopObject *shop = [shops_ objectAtIndex:0];
        return [NSString stringWithFormat:@"%@",userObject_.userName];
    }else{
        return [NSString stringWithFormat:@"%@",userObject_.userName];
    }
    
}



- (NSMutableDictionary *)getAllOrderSum:(NSString*)shopid {
    NSString* sql =@"";
    NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
    
    if ([self getShopList].count==0) {
        [dict setObject:[NSNumber numberWithInt:0] forKey:@"cnt"];
        [dict setObject:[NSNumber numberWithInt:0] forKey:@"totalmoney"];
        return dict;
    }
    
    sql = [NSString stringWithFormat:@"select ifnull(sum(a1.amount),0) as cnt,ifnull(sum(a2.sale*a1.amount),0) as totalmoney from g_meeting a1 left join v_g_spdm a2 on a1.code=a2.code and a1.colorid=a2.colorid where a1.amount>0 and a2.n_status=0"];
    
    if (shopid) {
        sql = [sql stringByAppendingFormat:@" AND a1.shopid = '%@'",shopid];
    }
    
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
       
        [dict setObject:[rs stringForColumn:@"cnt"] forKey:@"cnt"];
        [dict setObject:[rs stringForColumn:@"totalmoney"] forKey:@"totalmoney"];
        
        return dict;
    }
    
    return dict;
}


-(void)Copyorder:(NSString*)usercode code:(NSArray *)code FromShopid:(NSString *)fromShopid ToShopid:(NSString *)toShopid withTime:(int)times{
    if (code) {
        
        for (ProductObject *obj in code) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *formattedString = [dateFormatter stringFromDate:[NSDate date]];
            //       [db_ beginTransaction];
            NSString* sql = [NSString stringWithFormat:@"delete from g_meeting where shopid = '%@' and code = '%@'",toShopid,obj.pCode];
            BOOL r = [self excuteSQL:sql];
            if (!r) {
                NSLog(@"error:sql:%@",sql);
            }
            sql = [NSString stringWithFormat:@"insert into  g_meeting (scripno,shopid,iotime,code,colorid,xsize,amount,price,rebate,sale,orgprice,c_zuangtm,n_sample,usercode,maxSynID)  select scripno,'%@','%@',code,colorid,xsize,amount*%d,price,rebate,sale,orgprice,c_zuangtm,n_sample,usercode,'' from g_meeting where shopid = '%@' and amount<>0 and code = '%@'",toShopid,formattedString,times,fromShopid,obj.pCode];
            [self excuteSQL:sql];
            
            [[DataManager sharedManager]deleleremovedproductorder:toShopid];
            //        [db_ commit];
        }
    }
    else
    {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//        NSString *formattedString = [dateFormatter stringFromDate:[NSDate date]];
//        [db_ beginTransaction];
        /*
        NSString* sql = [NSString stringWithFormat:@"delete from g_meeting where shopid = '%@' ",toShopid];
        [self excuteSQL:sql];
         */
        
        NSString* sql = [NSString stringWithFormat:@"update g_meeting set amount = 0,MaxSynID = '' where shopid = '%@' ",toShopid];
        [self excuteSQL:sql];
        NSLog(@"%@",sql);
        
//        NSMutableArray *array = [[NSMutableArray alloc]init];
//        sql = [NSString stringWithFormat:@"select * from g_meeting where shopid = '%@' and amount = 0 ",toShopid];
//        FMResultSet *rs = [db_ executeQuery:sql];
//        while ([rs next]) {
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//            [dic setObject:[rs stringForColumn:@"code"] forKey:@"code"];
//            [dic setObject:[rs stringForColumn:@"colorid"] forKey:@"colorid"];
//            [dic setObject:[rs stringForColumn:@"xsize"] forKey:@"xsize"];
//            [array addObject:dic];
//        }
//        for (int i=0; i<array.count; i++) {
//            for (int j=i+1; j<array.count; j++) {
//                NSDictionary *dic = [array objectAtIndex:i];
//                NSDictionary *dic1 = [array objectAtIndex:j];
//                if([[dic objectForKey:@"code"] isEqualToString:[dic1 objectForKey:@"code"]]&&[[dic objectForKey:@"colorid"] isEqualToString:[dic1 objectForKey:@"colorid"]])
//                {
//                    NSString* sql = [NSString stringWithFormat:@"delete from g_meeting where shopid = '%@' and amount = 0 and code = '%@' and colorid = '%@' and xsize = '%@' ",toShopid,[dic1 objectForKey:@"code"],[dic1 objectForKey:@"colorid"],[dic1 objectForKey:@"xsize"]];
//                    [self excuteSQL:sql];
//                }
//            }
//        }
        /*
        sql = [NSString stringWithFormat:@"delete from g_meeting where shopid = '%@' and xsize not in(select min(xsize) from g_meeting where shopid = '%@' group by code,colorid)",toShopid,toShopid];
        [self excuteSQL:sql];
        */
        sql = [NSString stringWithFormat:@"delete  from g_meeting where shopid='%@' and code||'_'||colorid in (select code||'_'||colorid from g_meeting where shopid='%@' and amount>0)",toShopid,fromShopid];
        [self excuteSQL:sql];
        
        NSLog(@"%@",sql);
        
        sql = [NSString stringWithFormat:@"insert into g_meeting(shopid,code,colorid,xsize,amount,MaxSynID) select '%@',code,colorid,xsize,amount*%d,'' from g_meeting where shopid='%@' and amount>0 ",toShopid,times,fromShopid];
        [self excuteSQL:sql];
        NSLog(@"%@",sql);
        
        [[DataManager sharedManager]deleleremovedproductorder:toShopid];
    }
//    [db_ commit];
}

-(void)setmatching:(NSString *)type childtype:(NSString *)childtype typeno:(int)typeno num:(NSDictionary *)numdic sizearr:(NSArray *)sizearr
{
    NSString *sql = [NSString stringWithFormat:@"delete from setmatching where groupid = %d",typeno];
    [self excuteSQL:sql];
    for (int i=0; i<sizearr.count; i++) {
        SizeObject *sizeobject = [sizearr objectAtIndex:i];
        NSString *str=[numdic objectForKey:sizeobject.sSizeName];
        NSString *sql = [NSString stringWithFormat:@"insert into setmatching values(%d,'%@','%@','%@','%@')",typeno,type,childtype,sizeobject.sSizeName,str];
        [self excuteSQL:sql];
    }
}

-(NSArray*)getmatching:(NSString *)type childtype:(NSString *)childtype
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    NSString *sql = [NSString stringWithFormat:@"select * from setmatching where grouptype = '%@' and childgrouptype = '%@'",type,childtype];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *str = [self createSetObject:rs];
        [array addObject:str];
    }
    return array;
}

-(void)checkShop:(ShopObject *)obj
{
    [WaitTooles showHUD:@"正在检查"];
    [[WebServiceManager sharedManager ] checkShop:obj.shopID completion:^(NSArray *checkshop)
     {
         [WaitTooles removeHUD];
         NSDictionary *dic = [checkshop objectAtIndex:0];
         NSString *str = [dic objectForKey:@"cMsg"];
         NSArray *strarr = [str componentsSeparatedByString:@"HHHH"];
         NSString *str1 = [NSString stringWithFormat:@""];
         for (int i=0; i<strarr.count; i++) {
             NSString *str2 = [strarr objectAtIndex:i];
             str1 = [str1 stringByAppendingFormat:@"%@",str2];
             str1 = [str1 stringByAppendingString:@"\n"];
         }
         if (str&&![str isEqualToString:@""]) {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:str1 delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
         }
         else
         {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"未知错误，请联系工作人员" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
         }
         
     }];
}

-(void)veriShop:(NSString *)usercode password:(NSString *)password shopid:(NSString *)shopid
{
    [WaitTooles showHUD:@"正在审核"];
    [[WebServiceManager sharedManager ] VeriShop:usercode password:password shopid:shopid completion:^(NSArray *verishop)
     {
         
         
         
         [WaitTooles removeHUD];
         
         
         if (verishop==nil) {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"审核失败" message:@"请联系管理员" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
             return ;
         }
         
//         NSDictionary *dic = [verishop objectAtIndex:0];
//         NSString *str = [dic objectForKey:@"cMsg"];
//         NSArray *strarr = [str componentsSeparatedByString:@"HHHH"];
//         NSString *str1 = [NSString stringWithFormat:@""];
//         for (int i=0; i<strarr.count; i++) {
//             NSString *str2 = [strarr objectAtIndex:i];
//             str1 = [str1 stringByAppendingFormat:@"%@",str2];
//             str1 = [str1 stringByAppendingString:@"\n"];
//         }
         
         NSDictionary *dic = [verishop objectAtIndex:0];
         int result = [[dic objectForKey:@"result"] intValue];
         
         if (result==0 ) {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"审核失败" message:[dic objectForKey:@"cMsg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
         }
         else
         {
             showMessage(@"审核成功");
             
             ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
             shopobj.bCheck = 1;
             NSString *sql = [NSString stringWithFormat:@"update shops set bcheck = 1 where shopid = '%@'",shopid];
             [self excuteSQL:sql];
         }
     }];
}

-(void)veriShop:(NSString *)u_id shopid:(NSString *)shopid
{
    [WaitTooles showHUD:@"正在审核"];
    [[WebServiceManager sharedManager ] VeriShop:u_id shopid:shopid completion:^(NSArray *verishop)
     {
         [WaitTooles removeHUD];
         NSDictionary *dic = [verishop objectAtIndex:0];
         NSString *str = [dic objectForKey:@"cMsg"];
         NSArray *strarr = [str componentsSeparatedByString:@"HHHH"];
         NSString *str1 = [NSString stringWithFormat:@""];
         for (int i=0; i<strarr.count; i++) {
             NSString *str2 = [strarr objectAtIndex:i];
             str1 = [str1 stringByAppendingFormat:@"%@",str2];
             str1 = [str1 stringByAppendingString:@"\n"];
         }
         if (str&&![str isEqualToString:@""]) {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:str1 delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
         }
         else
         {
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"订单成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
             [alert show];
             
             ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
             shopobj.bCheck = 1;
             NSString *sql = [NSString stringWithFormat:@"update shops set bcheck = 1 where shopid = '%@'",shopid];
             [self excuteSQL:sql];
         }
     }];
}

-(void)setnewServerIP:(NSString *)url
{
    address = url;
}

-(NSString *)getnewServerIP
{
    return address;
}

-(NSArray *)issizecancel:(NSString *)code colorid:(NSString *)colorid
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    NSString *sql = [NSString stringWithFormat:@"select sizelist from g_size where code = '%@'",code];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        NSString *str = [self createSizeGroupObject:rs];
        NSArray *sizes = [str componentsSeparatedByString:@"|"];
        for (NSString *size in sizes) {
            [array addObject:size];
        }
    }
    return array;
}

-(void)deleleremovedproductorder:(NSString *)shopid
{
//    NSMutableArray *orderarray = [[NSMutableArray alloc]init];
//    NSString *sql = [NSString stringWithFormat:@"select * from g_meeting where shopid = '%@' and amount <>0",shopid];
//    FMResultSet *rs = [db_ executeQuery:sql];
//    while ([rs next]) {
//        // NSString *str = [self createSizeGroupObject:rs];
//        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//        [dic setObject:[rs stringForColumn:@"code"] forKey:@"code"];
//        [dic setObject:[rs stringForColumn:@"colorid"] forKey:@"colorid"];
//        [orderarray addObject:dic];
//    }
//    for (int i=0; i<orderarray.count; i++) {
//        NSDictionary *dic = [orderarray objectAtIndex:i];
//        NSMutableArray *array = [[NSMutableArray alloc]init];
//        sql = [NSString stringWithFormat:@"select * from v_g_spdm where code = '%@' and colorid = '%@'",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
//        rs = [db_ executeQuery:sql];
//        while ([rs next]) {
//           // NSString *str = [self createSizeGroupObject:rs];
//            [array addObject:@"0"];
//        }
//        if (array.count==0) {
//            NSString *sql = [NSString stringWithFormat:@"delete from g_meeting where code = '%@' and colorid = '%@' ",[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
//            [self excuteSQL:sql];
//        }
//    }
}
-(NSString *)getgroupno:(NSString *)keyname
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    NSString *sql = [NSString stringWithFormat:@"select * from ReferencePara where Name = '%@'",keyname];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *groupno;
    while ([rs next]) {
        groupno = [rs stringForColumn:@"ID"];
       // NSString *str = [self createSizeGroupObject:rs];
        [array addObject:@"0"];
    }
    if (array.count==1) {
        return groupno;
    }
    else
    {
        return @"error";
    }
}
-(void)RunBlockAfterDelay:(NSTimeInterval)delay completion:(block)completion
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
                   dispatch_get_current_queue(), completion);
}

-(NSArray *)getTipsarray
{
    return TipUpdates_;
}

-(void)setTipsarray:(NSArray *)array
{
    TipUpdates_ = array;
}

-(void)showtip
{
    NSArray *tips = [[DataManager sharedManager]getTipsarray];
    if (tips.count==0) {
        return;
    }
    NSDictionary *tipdic = [tips objectAtIndex:tips.count-1];
    
    [self performSelectorOnMainThread:@selector(addTipView:) withObject:tipdic waitUntilDone:YES];
    
}

- (void)addTipView:(NSDictionary *)dic{
    UIWindow *w = [UIApplication sharedApplication].keyWindow;
    TipView *tipview = [[TipView alloc]initWithdic:dic];
    [w addSubview:tipview];
}

-(NSString *)getspdmorder:(ProductObject *)obj titlename:(NSString *)titlename
{
    NSString *sql = [NSString stringWithFormat:@"select * from v_g_spdm where code = '%@' and colorid = '%@'",obj.pCode,obj.pColorCode];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *content;
    while ([rs next]) {
        content = [rs stringForColumn:titlename];
        // NSString *str = [self createSizeGroupObject:rs];
    }
    return content;
}

-(int)gettypeno:(NSString *)name
{
    NSString *sql = [NSString stringWithFormat:@"select * from ReferencePara where Name = '%@'",name];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *groupno;
    while ([rs next]) {
        groupno = [rs stringForColumn:@"groupno"];
        // NSString *str = [self createSizeGroupObject:rs];
    }
    return [groupno intValue];
}

-(void)deleteuserandshops:(NSString *)usercode password:(NSString *)password
{
    NSString *sql = [NSString stringWithFormat:@"delete from shops where usercode = '%@' and password = '%@' ",usercode,password];
    [self excuteSQL:sql];
}

-(void)adduserandshops:(NSString *)usercode password:(NSString *)password username:(NSString *)username biurl:(NSString *)biurl inputtype:(int)inputtype shops:(NSDictionary *)shops
{
    NSString *sql = [NSString stringWithFormat:@"insert into shops(usercode,password,username,biurl,inputtype,shopid,shopname,border,bcheck) values('%@','%@','%@','%@','%d','%@','%@','%@','%@')",usercode,password,username,biurl,inputtype,[shops objectForKey:@"shopid"],[shops objectForKey:@"shopname"],[shops objectForKey:@"bOrder"],[shops objectForKey:@"bCheck"]];
    BOOL r = NO;
    r = [self excuteSQL:sql];
    if (r==NO){
        NSLog(@"error,%@",sql);
    }
}

-(NSString *)getusername:(NSString *)usercode
{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *username;
    while ([rs next]) {
        username = [rs stringForColumn:@"username"];
    }
    return username;
}

-(NSString *)getbiurl:(NSString *)usercode
{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *biurl;
    while ([rs next]) {
        biurl = [rs stringForColumn:@"biurl"];
    }
    return biurl;
}

-(NSString *)getinputtype:(NSString *)usercode
{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *inputtype;
    while ([rs next]) {
        inputtype = [rs stringForColumn:@"inputtype"];
    }
    return inputtype;
}

- (BOOL)checkusercodeByID:(NSString *)uID{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where u_id = '%@'",uID];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return YES;
    }
    return NO;
}

-(BOOL)checkusercode:(NSString *)usercode password:(NSString *)password
{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'and password = '%@'",usercode,password];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return YES;
    }
    return NO;
}

-(BOOL)userExist:(NSString *)usercode{
    NSString *sql = [NSString stringWithFormat:@"select * from shops where usercode = '%@'",usercode];
    FMResultSet *rs = [db_ executeQuery:sql];
    while ([rs next]) {
        return YES;
    }
    return NO;
}

-(void)updateProductstatus:(NSArray *)array
{
    for (NSDictionary *dic in array) {
        NSString *sql = [NSString stringWithFormat:@"update v_g_spdm set n_status = '%@' where code = '%@' and colorid = '%@'",[dic objectForKey:@"n_status"],[dic objectForKey:@"code"],[dic objectForKey:@"colorid"]];
        [self excuteSQL:sql];
    }
}


- (void)forceUpdate:(DMCompletion)completion{
    
    [self refreshSaleSegmentTable:^(id res){
        
    }];
    
    [self refreshProductTable:^(id res){
        [self refreshProductColoridTable:^(id res){
            [self refreshProductPictureTable:^(id res){
                [self refreshSuitTable:^(id res){
                    NSLog(@"配装更新完毕");
        //            [self refreshSpdmStatusTimeTable:^(id res){
        //                NSLog(@"商品投产状态更新完毕");
//                    [self refreshSpdmSizeTable:^(id res){
                        NSLog(@"商品尺码表更新完毕");
                        [self refreshReferenceTable:^(id res){
                            [self refreshSizeTable:^(id res){
                                [self refreshg_SizeTable:^(id res){
                                    [self refreshColortblTable:^(id res){
                                        [self refreshXilieTable:^(id res){
                                            NSLog(@"更新商品系类表");
                                            [self refreshKuansTable:^(id res){
                                                NSLog(@"更新商品款式表");
                                                [self refreshKuanxTable:^(id res){
                                                    NSLog(@"更新商品款型表");
                                                    [self refreshXiaoxlTable:^(id res){
                                                        NSLog(@"更新商品小系列表");
                                                        [self refreshNianfTable:^(id res){
                                                            NSLog(@"更新商品年份表");
                                                            [self refreshJijieTable:^(id res){
                                                                NSLog(@"更新商品季节表");
                                                                [self refreshPingpTable:^(id res){
                                                                    NSLog(@"更新商品品牌表");
                                                                    completion(nil);
                                                                    [self deleteTable:@"g_meeting"];
                                                                    [self deleteTable:@"shops"];
                                                                    [self deleteTable:@"s_user"];
                                                                    [self deleteTable:@"tips"];
                                                                }];
                                                            }];
//                                                        }];
                                                    }];
                                                }];
                                            }];
                                        }];
                                        NSLog(@"更新商品颜色表");
                                    }];
                                }];
                               // [self deleteTable:@"g_meeting"];
                            }];
                        }];
                    }];
                }];
            }];
        }];
    }];
    
    [self refreshSpdmOrderTable:^(id res){
        
    }];
    

    

//    }];
}


- (void)resetOrderTable{
    ShopObject *shop = [self getCurrentShop];
    NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '' d_upid='' where shopid ='%@'",shop.shopID];
    [self excuteSQL:sql];
    
    [WaitTooles showHUD:@"正在提交订单，请稍后..."];
    [[AppManager sharedManager] pauseAutoUpdateSession];
    [[AppManager sharedManager] pauseAutoSubmitSession];
    [self performSelectorInBackground:@selector(forceSubmit:) withObject:nil];
}



- (void)forceSubmitAllOrder:(DMCompletion)completion{
    ShopObject *shop = [self getCurrentShop];
    //    UserObject *user = [self getUserObject];
    NSString *sql = [NSString stringWithFormat:@"select code,shopid,colorid,xsize,amount,usercode from g_meeting where shopid='%@' and MaxSynID = ''",shop.shopID];
    FMResultSet *rs = [db_ executeQuery:sql];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"order_%@_%@.txt",shop.shopID,[NSDate date]]];
    
    NSMutableString *order = [NSMutableString string];
    
    while ([rs next]) {
        NSString *shopid = [rs stringForColumn:@"shopid"];
        NSMutableArray *array = [dic objectForKey:shopid];
        if (array==nil) {
            array = [NSMutableArray array];
        }
        
        NSString *code = [rs stringForColumn:@"code"];
        
        NSString *colorid = [rs stringForColumn:@"colorid"];;
        NSString *size = [rs stringForColumn:@"xsize"];
        NSString *amount = [rs stringForColumn:@"amount"];
        
        NSString *orderString = [NSString stringWithFormat:@"%@,%@,%@,%@\n",code,colorid,size,amount];
        [order appendString:orderString];
    }
    
    if (order.length==0) {
        completion([NSArray array]);
        return;
    }
    
    [order writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSMutableDictionary *d = [NSMutableDictionary dictionary];
    [d setObject:order forKey:@"order"];
    [d setObject:completion forKey:@"completion"];

    [self performSelectorOnMainThread:@selector(sumbitTotalAllOrder:)
                           withObject:d
                        waitUntilDone:YES];
}

- (void)sumbitTotalAllOrder:(NSDictionary*)dic{
    ShopObject *shop = [self getCurrentShop];
    UserObject *user = [self getUserObject];
    
    NSString *order = [dic objectForKey:@"order"];
    DMCompletion completion = [dic objectForKey:@"completion"];
    
    
    
    [[WebServiceManager sharedManager] forceUpdateOrder:^(id res){
        
        NSArray *array = [res objectForKey:@"Table"];
        if (res==nil||array==nil) {
            completion(nil);
            return;
        }
        
        NSDictionary *d = [array objectAtIndex:0];
        
        NSString *ioresult = [d objectForKey:@"ioresult"];
        if (ioresult!=nil) {
            showMessage([d objectForKey:@"Result"]);
            completion(nil);
            
            return;
        }
        
        NSString *time = [d objectForKey:@"MaxSynID"];
        NSString *nowtime = [d objectForKey:@"MaxDatetime"];
        
        NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '%@',d_upid = '%@' where shopid = '%@' ",time,nowtime,shop.shopID];
        [self excuteSQL:sql];
        
        [WaitTooles removeHUD];
        
        completion([NSArray array]);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                           object:nil];
        
    }shop:shop.shopID orders:order user:user.userCode];
    
}

- (void)forceSubmit:(DMCompletion)completion{
    ShopObject *shop = [self getCurrentShop];
//    UserObject *user = [self getUserObject];
    NSString *sql = [NSString stringWithFormat:@"select code,shopid,colorid,xsize,amount,usercode from g_meeting where shopid='%@' and MaxSynID = ''",shop.shopID];
    FMResultSet *rs = [db_ executeQuery:sql];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"order_%@_%@.txt",shop.shopID,[NSDate date]]];
    
    NSMutableString *order = [NSMutableString string];
    
    while ([rs next]) {
        NSString *shopid = [rs stringForColumn:@"shopid"];
        NSMutableArray *array = [dic objectForKey:shopid];
        if (array==nil) {
            array = [NSMutableArray array];
        }
        
        NSString *code = [rs stringForColumn:@"code"];
        NSString *colorid = [NSString stringWithFormat:@"%03d",[rs intForColumn:@"colorid"]];
        NSString *size = [rs stringForColumn:@"xsize"];
        NSString *amount = [rs stringForColumn:@"amount"];
        
        NSString *orderString = [NSString stringWithFormat:@"%@,%@,%@,%@\n",code,colorid,size,amount];
        [order appendString:orderString];
    }
    
    if (order.length==0) {
        completion([NSArray array]);
        return;
    }
    
    [order writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

    NSMutableDictionary *d = [NSMutableDictionary dictionary];
    [d setObject:order forKey:@"order"];
    [d setObject:completion forKey:@"completion"];
    [self performSelectorOnMainThread:@selector(sumbitAllOrder:)
                           withObject:d
                        waitUntilDone:YES];
}


- (void)sumbitAllOrder2:(NSDictionary*)dic{
    ShopObject *shop = [self getCurrentShop];
    UserObject *user = [self getUserObject];
    
    NSString *order = [dic objectForKey:@"order"];
    DMCompletion completion = [dic objectForKey:@"completion"];
    
    
    
    [[WebServiceManager sharedManager] forceUpdateOrder:^(id res){
        
        NSArray *array = [res objectForKey:@"Table"];
        if (res==nil||array==nil) {
            completion(nil);
            return;
        }
        
        NSDictionary *d = [array objectAtIndex:0];
        
        NSString *ioresult = [d objectForKey:@"ioresult"];
        if (ioresult!=nil) {
            showMessage([d objectForKey:@"Result"]);
            completion(nil);
            
            return;
        }
        
        NSString *time = [d objectForKey:@"MaxSynID"];
        NSString *nowtime = [d objectForKey:@"MaxDatetime"];
        
        NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '%@',d_upid = '%@' where shopid = '%@' ",time,nowtime,shop.shopID];
        [self excuteSQL:sql];
        
        [WaitTooles removeHUD];
        
        completion([NSArray array]);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                           object:nil];
        
    }shop:shop.shopID orders:order user:user.userCode];
    
}

- (void)sumbitAllOrder:(NSDictionary*)dic{
    ShopObject *shop = [self getCurrentShop];
    UserObject *user = [self getUserObject];
    
    NSString *order = [dic objectForKey:@"order"];
    DMCompletion completion = [dic objectForKey:@"completion"];
    

    
    [[WebServiceManager sharedManager] forceIncreaseUpdateOrder:^(id res){
        
        NSArray *array = [res objectForKey:@"Table"];
        if (res==nil||array==nil) {
            NSString *ioresult = [res objectForKey:@"ioresult"];
            if (ioresult!=nil) {
                [WaitTooles removeHUD];
                showMessage([res objectForKey:@"Message"]);
            }
            
            
            completion(nil);
            return;
        }
        
        NSDictionary *d = [array objectAtIndex:0];
        
        NSString *ioresult = [d objectForKey:@"ioresult"];
        if (ioresult!=nil) {
            showMessage([d objectForKey:@"Result"]);
            completion(nil);
            
            return;
        }
        
        NSString *time = [d objectForKey:@"MaxSynID"];
        NSString *nowtime = [d objectForKey:@"MaxDatetime"];

        NSString *sql = [NSString stringWithFormat:@"update g_meeting set MaxSynID = '%@',d_upid = '%@' where shopid = '%@' ",time,nowtime,shop.shopID];
        [self excuteSQL:sql];
        
        [WaitTooles removeHUD];
        
        completion([NSArray array]);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"ordernumrefresh"
                                                           object:nil];
        
    }shop:shop.shopID orders:order user:user.userCode];

}



- (NSString *)getSubmitLastTime{
    ShopObject *shopobj = [[DataManager sharedManager]getCurrentShop];
    NSString *sql = [NSString stringWithFormat:@"select max(d_upid)  as max_time from g_meeting where  shopid = '%@'",shopobj.shopID];
    
    FMResultSet *rs = [db_ executeQuery:sql];
    NSString *d = @"无";
    while ([rs next]) {
        d = [rs stringForColumn:@"max_time"];
        if (d==nil) {
            d = @"无";
        }
        break;
    }
    
    if (d.length > 10) {
        d = [d substringWithRange:NSMakeRange(5, 11)];
    }
    
    return d;
}

- (void)copyDatabase{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths objectAtIndex:0];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd_HH:mm:ss";
    NSString* d = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString *path = [[AppManager sharedManager] getDatabasePath];
    NSString *dst = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"TUMeeting_%@.db",d]];
    [[NSFileManager defaultManager] copyItemAtPath:path toPath:dst error:nil];
}

-(NSString*) getuuid {
//    CFUUIDRef puuid = CFUUIDCreate( nil );
//    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
//    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
//    CFRelease(puuid);
//    CFRelease(uuidString);
    
    return [self macaddress];
}

- (NSString *) macaddress
{
    
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>=6.0){
        ASIdentifierManager *mgr = [ASIdentifierManager sharedManager];
        
        
        NSString *guid = [mgr.advertisingIdentifier UUIDString];
        NSLog(@"%@",guid);
        return guid;
    }else{
        int                    mib[6];
        size_t                len;
        char                *buf;
        unsigned char        *ptr;
        struct if_msghdr    *ifm;
        struct sockaddr_dl    *sdl;
        
        mib[0] = CTL_NET;
        mib[1] = AF_ROUTE;
        mib[2] = 0;
        mib[3] = AF_LINK;
        mib[4] = NET_RT_IFLIST;
        
        if ((mib[5] = if_nametoindex("en0")) == 0) {
            printf("Error: if_nametoindex error/n");
            return NULL;
        }
        
        if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
            printf("Error: sysctl, take 1/n");
            return NULL;
        }
        
        if ((buf = malloc(len)) == NULL) {
            printf("Could not allocate memory. error!/n");
            return NULL;
        }
        
        if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
            printf("Error: sysctl, take 2");
            return NULL;
        }
        
        ifm = (struct if_msghdr *)buf;
        sdl = (struct sockaddr_dl *)(ifm + 1);
        ptr = (unsigned char *)LLADDR(sdl);
        // NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
        NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
        free(buf);
        return [outstring uppercaseString];
    }
}


-(void)gettotalorderInfo{
    
    ShopObject *obj = [[DataManager sharedManager] getCurrentShop];
    NSDictionary* dict = [[DataManager sharedManager]getAllOrderSum:obj.shopID];
    
    [[WebServiceManager sharedManager] checktotal:[[DataManager sharedManager] getUserObject].userCode count:[dict objectForKey:@"cnt"] money:[dict objectForKey:@"totalmoney"] completion:^(NSArray *array){
        
        NSDictionary* serverdata = [array objectAtIndex:0];
        
        if ([[serverdata objectForKey:@"result"] isEqualToString:@"False"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"前后台数据不一致" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
            alert.tag = 502;
            [alert show];
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"前后台数据一致" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

- (void)verifyOrderWithServer:(DMCompletion)completion{
    ShopObject *obj = [[DataManager sharedManager] getCurrentShop];
    NSDictionary* dict = [[DataManager sharedManager]getAllOrderSum:obj.shopID];
    
    [[WebServiceManager sharedManager] checkShopTotal:[[DataManager sharedManager] getCurrentShop].shopID count:[dict objectForKey:@"cnt"] money:[dict objectForKey:@"totalmoney"] completion:^(NSArray *array){
        
        NSDictionary* serverdata = [array objectAtIndex:0];
        
        if ([[serverdata objectForKey:@"result"] isEqualToString:@"False"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"前后台数据不一致" message:@"是否重新上传订单" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认",nil, nil];
            alert.tag = 502;
            [alert show];
            completion(nil);
        }
        else{
            completion(serverdata);
        }
        
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 502) {
        if (buttonIndex==1) {
            
            [WaitTooles showHUD:@"提交订单"];
            [[AppManager sharedManager] forceSubmitAllOrder:^(id res){
                [WaitTooles removeHUD];
            }];
            
        }
    }
}

- (void)clear{
    NSString *sql = @"update g_meeting set maxsynid = ''";
    [self excuteSQL:sql];
}

@end
